In asp Net core auto enable cap transaction details

Time:2022-6-13

This article aims to describe how toASP.NET CoreIn the project, cap transactions are enabled in a simple way, because in our examples, they are directly demonstrated in a more intuitive way, and are not encapsulated. Some beginners don’t know much about it, so they ask me how to encapsulate it. This article is mainly a simple demonstration.

In this example, we are mainly based on Entity Framework For demonstration, if you use other ORM principles similar, you can refer to them.

1、 Publisher transaction

Because most people areWeb , so you can useASP.NET Core Of course, the filter can also be implemented through the middleware. The principle is the same.

1. Create aTypeFilter, namedCapTransactionFilterAttribute


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, when transaction control is requiredAction Add on[TypeFilter(typeof(CapTransactionFilterAttribute))]It 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 transaction

Automatic transactions on the consumer side are mainly usedCAP Filter provided for opening, andCAP Version 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 filters


services.AddCap(opt =>
{
    // ***
}.AddSubscribeFilter<MyCapFilter>();

The above is a simple example of the consumer side.

This is about ASP.NET Core Auto enable inCAP This is the end of the article on transaction details. For more information, please refer to ASP.NET Core Please search the previous articles of developeppaer or continue to browse the related articles below. I hope you will support developeppaer in the future!

Recommended Today

Husky for automatic front-end code formatting

in usegit hooksWe usually usehuskyTool that enables localgit hooksIt becomes simpler. We usually use it this way; 1. Install husky npm install husky –save-dev or yarn add husky -D 2. Configuring husky files //.huskyrc.json { “hooks”:{ “pre-commit”:”npm test && npm run foo” } } or //package.json { “husky”:{ “hooks”:{ “pre-commit”:”npm test && npm run foo” […]