WebApi异步操作过滤器事务

时间:2015-08-18 01:28:47

标签: asp.net-web-api transactionscope

到目前为止,我们已经实现了同步WebApi方法。每个操作都有一个在操作调用之前创建的事务,如果一切成功,则该事务在调用结束时提交。如果我现在需要实现异步操作,我将如何更改下面的操作过滤器仍然正确提交事务?或者我需要实现DelegatingHandler?提前谢谢。

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class TransactionAttribute : ActionFilterAttribute
{
    private IWindsorContainer Container
    {
        get { return IocContainer.Container; }
    }

    private WebRequestContext WebRequestContext
    {
        get
        {
            var webRequestContext = Container.Resolve<WebRequestContext>();
            return webRequestContext;
        }
    }

    private TransactionScope TransactionScope
    {
        get { return WebRequestContext.TransactionScope; }
        set { WebRequestContext.TransactionScope = value; }
    }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var transactionOptions = new TransactionOptions
        {
            IsolationLevel = IsolationLevel.ReadCommitted 
        };
        TransactionScope = new TransactionScope(TransactionScopeOption.Required,
            transactionOptions);

        base.OnActionExecuting(actionContext);
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        using (TransactionScope)
        {
            base.OnActionExecuted(actionExecutedContext);
            if (IsSuccessfulInvocation(actionExecutedContext))
            {
                TransactionScope.Complete();
            }
        }
    }

    private static bool IsSuccessfulInvocation(HttpActionExecutedContext actionExecutedContext)
    {
        return actionExecutedContext.Exception == null;
    }

0 个答案:

没有答案