I have a filter like this one:
public class CustomFilterAttribute : ActionFilterAttribute, IAuthorizationFilter
{
public MyPropery Property { get; set; }
....
}
I need it to be run for every actions in my project
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?
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
Register everything you need in autofac
Register your global filter like that
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!
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:
Note that by passing in the
Controller
class into the extensionAsActionFilterFor()
we are telling AutoFac to apply this filter to all classes that derive from theController
class (which, in MVC, is all controllers). Since we are callingAsActionFilterFor()
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:If your action takes a parameter, use the
default
keyword to specify: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: