How to automatically enable CAP transactions in ASP.NET Core
Editor to share with you how to automatically enable CAP transactions in ASP.NET Core, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
I. Publishing transaction
Since most people use Web, it can be done through the use of ASP.NET Core filters and, of course, through middleware, the principle is consistent.
1. Create a TypeFilter named CapTransactionFilterAttribute
Public class CapTransactionFilterAttribute: TypeFilterAttribute {public CapTransactionFilterAttribute (): base (typeof (TransactionActionFilter)) {} public class TransactionActionFilter: IActionFilter {private IDbContextTransaction _ transaction; public void OnActionExecuting (ActionExecutingContext context) {var dbContext = context.HttpContext.RequestServices.GetRequiredService (); var capPublisher = context.HttpContext.RequestServices.GetService (); _ transaction = dbContext.Database.BeginTransaction (capPublisher) } public void OnActionExecuted (ActionExecutedContext context) {if (context.Exception = = null) {_ transaction.Commit ();} else {_ transaction.Rollback ();} _ transaction?.Dispose ();}
2. Usage: add [TypeFilter (typeof (CapTransactionFilterAttribute))] to the Action where transaction control is required to take effect.
[Route ("~ / ef/trans-filter")] [TypeFilter (typeof (CapTransactionFilterAttribute))] public IActionResult EntityFrameworkWithTransactionFilter ([FromServices] AppDbContext dbContext) {dbContext.Persons.Add (new Person () {Name = "ef.transaction"}); _ capBus.Publish ("sample.rabbitmq.mysql", DateTime.Now); dbContext.SaveChanges (); return Ok ();} II. Consumer transaction
The automatic transaction on the consumer side is mainly enabled by the filter provided by CAP, and the CAP version is greater than 5.1.0.
1. Create a CAP filter public class MyCapFilter: SubscribeFilter {private readonly AppDbContext _ dbContext; private IDbContextTransaction _ transaction; public MyCapFilter (AppDbContext dbContext) {_ dbContext = dbContext;} public override void OnSubscribeExecuting (ExecutingContext context) {_ transaction = _ dbContext.Database.BeginTransaction ();} public override void OnSubscribeExecuted (ExecutedContext context) {_ transaction.Commit () } public override void OnSubscribeException (DotNetCore.CAP.Filter.ExceptionContext context) {_ transaction.Rollback ();}} 2, configure filter services.AddCap (opt = > {/ / *}. AddSubscribeFilter (); above is all the content of the article "how to automatically enable CAP transactions in ASP.NET Core". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!