在ASP.NET MVC 2上,我有一个名为[Transaction]的ActionFilterAttribute,它在执行操作之前启动NHibernate事务,然后提交或回滚它,具体取决于是否抛出了异常. ISession实例是HttpRequestScoped()并由
Autofac注入.它看起来像这样并且效果很好:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public sealed class TransactionAttribute : ActionFilterAttribute { private ITransaction transaction; public TransactionAttribute() { this.Order = 0; } public ISession Session { get; set; } public override void OnActionExecuted( ActionExecutedContext filterContext) { if (this.Session != null && this.transaction != null) { try { if (this.transaction.IsActive) { if (filterContext.Exception == null) { this.transaction.Commit(); } else { this.transaction.Rollback(); } } } finally { this.transaction.Dispose(); this.transaction = null; } } } public override void OnActionExecuting( ActionExecutingContext filterContext) { if (this.Session != null) { this.transaction = this.Session.BeginTransaction(); } } }
太棒了. Seems to be a common pattern.
在ASP.NET MVC 3中,我在“Breaking Changes”(强调我的)下看到了这个小小的模糊:
In prevIoUs versions of ASP.NET MVC,action filters were created per request except in a few cases. This behavior was never a guaranteed behavior but merely an implementation detail and the contract for filters was to consider them stateless. In ASP.NET MVC 3,filters are cached more aggressively. Therefore,any custom action filters which improperly store instance state might be broken.
哎呀.
>这是否意味着如果我升级到MVC 3,我就会被冲洗?
>如果每个请求不再实例化操作过滤器,我们如何将请求范围的依赖项添加到我们的操作过滤器中?
感谢您的任何见解.
解决方法
我刚在谷歌论坛上问了一个类似的问题.
这是链接 https://groups.google.com/forum/#!topic/autofac/a0qqp2b3WA8
这是链接 https://groups.google.com/forum/#!topic/autofac/a0qqp2b3WA8
我得到了答案:
builder.RegisterType<ExtensibleActionInvoker>().As<IActionInvoker>(); builder.RegisterControllers(Assembly.GetExecutingAssembly()).InjectActionInvoker();