Automatically enable CAP transaction details in ASP. NET Core
- 2021-12-04 09:56:07
- OfStack
The purpose of this article is to describe how to use the
ASP.NET Core
Project and a simple way to enable CAP transactions, because in our examples are more intuitive way of direct demonstration, there is no encapsulation, some beginners students are not very good, find and ask me how to encapsulate, this article is mainly a simple demonstration.
In this example, we are primarily based on the
Entity Framework
To demonstrate, if you use other Orm principles similar, you can refer to it.
1. Publisher-side transactions
Because most people are in
Web
You can use it by using the
ASP.NET Core
Filter way, of course, can also be through middleware, the principle is 1 to.
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<AppDbContext>();
var capPublisher = context.HttpContext.RequestServices.GetService<ICapPublisher>();
_transaction = dbContext.Database.BeginTransaction(capPublisher);
}
public void OnActionExecuted(ActionExecutedContext context)
{
if (context.Exception == null)
{
_transaction.Commit();
}
else
{
_transaction.Rollback();
}
_transaction?.Dispose();
}
}
}
2. Usage mode, in the need for transaction control
Action
Add [
TypeFilter(typeof(CapTransactionFilterAttribute
))] takes 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();
}
2. Consumer transactions
Consumer automatic transactions mainly use
CAP
The provided filter is required to open
CAP
Version is greater than 5.1. 0.
1. Create an 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 the filter
services.AddCap(opt =>
{
// ***
}.AddSubscribeFilter<MyCapFilter>();
The above is a simple example of the consumer side.