Register global filters in ASP.Net MVC 4 and Autofac

后端 未结 2 1723
感情败类
感情败类 2020-12-13 18:22

I have a filter like this one:

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


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 19:05

    You should now use Pete's solution now to do this. Thanks to him for an updated solution.

    I finally made it, here is how to do it:

    First create your attribute with a constructor with all dependencies

    public class CustomFilterAttribute : ActionFilterAttribute, IAuthorizationFilter
    {
        private IProperty _property;
    
        public CustomFilterAttribute(IProperty repository)
        {
            _property = property;
        }
        ....
     }
    

    Register everything you need in autofac

    var builder = new ContainerBuilder();
    builder.RegisterControllers(Assembly.GetExecutingAssembly());
    
    builder.RegisterType().As();
    builder.RegisterType().SingleInstance();
    
    builder.RegisterFilterProvider();
    
    IContainer container = builder.Build();
    
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    

    Register your global filter like that

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(DependencyResolver.Current.GetService());
    }
    

    Make sure in your global.asax you register first Autofac and then the global filters.

    Now, you don't need property injection anymore, constructor injection will work fine which is a good thing!

提交回复
热议问题