.NET Core中的事务注释属性 [英] Transactional annotation attribute in .NET Core

查看:165
本文介绍了.NET Core中的事务注释属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是很好奇,在Java中,有一个 @Transactional 属性可以放在方法名称上方,并且由于几乎每个应用程序服务方法都使用事务,因此可以简化代码.

I am just curious, in Java, there is a @Transactional attribute which can be placed above the method name and because almost every application service method use's transaction, it may simplify the code.

// Java example
public class FooApplicationService {
    @Transactional
    public void DoSomething() 
    {
        // do something ...
    }
}

当前是在.NET中完成的方式

This is currently how it is done in .NET

// .NET example
public class FooApplicationService {
    public void DoSomething() 
    {
        using (var transaction = new TransactionScope())
        {
            // do something ...
            transaction.Complete();
        }
    }
}

是否也可以通过.NET Core中的注释属性来管理事务的通行证?

Is it possible to manage transaction's via annotation attribute in .NET Core too?

推荐答案

您可以为此创建操作过滤器

You can create action filter for this purpose

//filter factory is used in order to create new filter instance per request
public class TransactionalAttribute : Attribute, IFilterFactory
{
    //make sure filter marked as not reusable
    public bool IsReusable => false;

    public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
    {
        return new TransactionalFilter();
    }

    private class TransactionalFilter : IActionFilter
    {
        private TransactionScope _transactionScope;

        public void OnActionExecuting(ActionExecutingContext context)
        {
            _transactionScope = new TransactionScope();
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            //if no exception were thrown
            if (context.Exception == null)
                _transactionScope.Complete();
        }
    }
}

并像这样使用它

public class HomeController : Controller {
    //...    

    [Transactional]
    public IActionResult Test() { /*some code */ }

    //...
}

注意

@cmart 的评论中所述,有一种更优雅的解决方案可以使用 IAsyncActionFilter

As mentioned in comments by @cmart there is more elegant solution to accomplish this with using IAsyncActionFilter

public class TransactionalAttribute : Attribute, IAsyncActionFilter
{
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        using (var transactionScope = new TransactionScope())
        {
            await next();
            transactionScope.Complete();
        }
    }
}

这篇关于.NET Core中的事务注释属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆