DEV Community

Xhanti Mda
Xhanti Mda

Posted on

Filters with Dependency Injection in ASP.NET CORE

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.


An example of a filter implementing IFilterFactory

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.

An example of registering a filter.
An example of how the ServiceFilterAttribute can be used

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.

An example of how the TypeFilterAttribute can be used

The sample code can be found here

Top comments (0)