ASP.NET MVC 3,动作过滤器和Autofac依赖注入

Nic*_*cki 6 autofac action-filter asp.net-mvc-3

ASP.NET MVC 2上,我有一个ActionFilterAttribute调用[Transaction],在执行操作之前启动一个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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

太棒了.似乎是一种常见的模式.

ASP.NET MVC 3笔记中,我在"突破性变化"(强调我的)下看到了这个小小的模糊:

在以前版本的ASP.NET MVC中,除少数情况外,每个请求都创建了操作过滤器.这种行为从来都不是保证行为,而只是一个实现细节,而过滤器的合同是将它们视为无状态.在ASP.NET MVC 3中,过滤器被更积极地缓存.因此,任何不正确地存储实例状态的自定义操作过滤器都可能被破坏.

哎呀.

  • 这是否意味着如果我升级到MVC 3,我会被冲洗?
  • 如果每个请求不再实例化操作过滤器,我们如何将请求范围的依赖项添加到我们的操作过滤器中?

感谢您的任何见解.

dmo*_*ord 6

我刚在谷歌论坛上问了一个类似的问题.这是一个链接https://groups.google.com/forum/#!topic/autofac/a0qqp2b3WA8

我得到了答案:

builder.RegisterType<ExtensibleActionInvoker>().As<IActionInvoker>();


builder.RegisterControllers(Assembly.GetExecutingAssembly()).InjectActionInvoker();
Run Code Online (Sandbox Code Playgroud)

然后,您可以在属性中使用属性注入.