在ASP.Net MVC 4和Autofac注册全局过滤器

问题描述:

我有这样一个过滤器:

public class CustomFilterAttribute : ActionFilterAttribute, IAuthorizationFilter
{
    public MyPropery Property { get; set; }
    ....
}

我需要为每一个动作在我的项目上运行

I need it to be run for every actions in my project

我试图在GlobalFilters登记,但我的财产不会被注入

I tried to register it in the GlobalFilters but my property doesn't get injected

我试过该解决方案登记我的过滤器,但它不会被调用。

I tried This solution to register my filter but it doesn't get called

这是如何做到这一点任何想法?

Any idea on how to do that?

有在AutoFac注册MVC全局筛选的新途径。首先,删除从过滤器注册您的 RegisterGlobalFilters ,因为我们将有Autofac处理他们加入到我们的控制器/行动,而不是MVC。

There's a new way of registering MVC global filters in AutoFac. First, remove the filter registration from your RegisterGlobalFilters because we will have Autofac handle adding them to our controllers/actions instead of MVC.

然后,如下注册您的容器:

Then, register your container as follows:

var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());

builder.RegisterType<MyProperty>().As<IProperty>();

builder.Register(c => new CustomFilterAttribute(c.Resolve<IProperty>()))
                .AsActionFilterFor<Controller>().InstancePerHttpRequest();

builder.RegisterFilterProvider();

IContainer container = builder.Build();

DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

注意,通过传递控制器类到延长 AsActionFilterFor()我们告诉AutoFac应用此过滤到从控制器类(其中,MVC,是所有控制器)派生的所有类。既然我们呼吁 AsActionFilterFor()不带任何参数,我们还规定,我们希望有应用于指定控制器中的所有动作的过滤器。如果你想你的过滤器适用于选择控制器和动作,你可以使用拉姆达前pressions像这样:

Note that by passing in the Controller class into the extension AsActionFilterFor() we are telling AutoFac to apply this filter to all classes that derive from the Controller class (which, in MVC, is all controllers). Since we are calling AsActionFilterFor() without any arguments, we are also specifying we want to have the filter applied to all actions within the specified controllers. If you want to apply your filter to a select controller and action, you can use lambda expressions like so:

builder.Register(c => new CustomFilterAttribute(c.Resolve<IProperty>()))
    .AsActionFilterFor<HomeController>(c => c.Index())
    .InstancePerHttpRequest();

如果你的动作需要一个参数,使用默认关键字指定:

If your action takes a parameter, use the default keyword to specify:

builder.Register(c => new CustomFilterAttribute(c.Resolve<IProperty>()))
    .AsActionFilterFor<HomeController>(c => c.Detail(default(int)))
    .InstancePerRequest();

请注意,你必须使用基于您注册什么类型的过滤器不同的扩展方法,这里有支持的过滤器类型:

Note that you have to use a different extension method based on what type of filter you are registering, here are the supported filter types:


  • AsActionFilterFor

  • AsAuthorizationFilterFor

  • AsExceptionFilterFor

  • AsResultFilterFor