Filters with Dependency Injection in ASP.NET CORE
Xhanti Mda
Posted on March 18, 2019
Recently I wanted to add a logger to a custom authorization filter(which was not the best idea) but I didn't want to new up an instance inside the filter, I wanted DI to handle all of that for me.
I did some digging and came across the TypeFilterAttribute, ServiceFilterAttribute and the IFilterFactory.
IFilterFactory
IFilterFactory interface allows you to create an instance of your filter by implementing the CreateInstance method inside your filter.
When MVC invokes a filter, it first tries to cast it to an IFilterFactory. If that cast succeeds, it then calls the CreateInstance method.
TypeFilter & ServiceFilter
The ServiceFilterAttribute implements the IFilterFactory. IFilterFactory exposes the CreateInstance method for creating an IFilterMetadata instance. The CreateInstance method loads the specified type from the container.
Filters used with the ServiceFilterAttribute need to be registered with the container.
The TypeFilterAttribute is similar to the ServiceFilterAttribute, but its type isn't resolved directly from the DI container. It instantiates the type by using Microsoft.Extensions.DependencyInjection.ObjectFactory.
This means that types referenced using the TypeFilterAttribute don't need to be registered with the container first and the TypeFilterAttribute can optionally accept constructor arguments for the type.
When using the TypeFilterAttribute, setting IsReusable is a hint that the filter instance may be reused outside of the request scope it was created within. The framework provides no guarantees that a single instance of the filter will be created. Avoid using IsReusable when using a filter that depends on services with a lifetime other than singleton.
The sample code can be found here
Posted on March 18, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 3, 2023