ServiceFilter and TypeFilter – what is the difference in injection those filters?

According to Pro ASP.NET Core MVC 2 book (download). Chapter 19: Filters, page # 615

When using the TypeFilter attribute, a new instance of the filter
class is created for every request. This is the same behavior as
applying a filter directly as an attribute, except that the TypeFilter
attribute allows a filter class to declare dependencies that are
resolved through the service provider. The ServiceFilter attribute
goes a step further and uses the service provider to create the filter
object. This allows filter objects to be placed under life-cycle
management as well.

THE DIFFERENCE
Since the ServiceFilter uses the ServiceProvider to resolve the instance of the filter in question, you have control over the lifecycle of the filter which is registered in the startup class:

services.AddSingleton<TimeFilter>();

From above line of code, the TimeFilter will only be created once for the MVC application lifecycle (not for each http request life cycle or when client asks for it) that will serve for all the http requests which is not possible using TypeFilter because there is no way you can instruct MVC framework when to instantiate and dispose the filter used under TypeFilter.

If the filter is registered as Singleton then only one instance of that filter is created which means less work for CLR which is unlike in case of TypeFilter that creates new instance of filter class for each http request.

THE USAGE
Say you have a TypeFilter applied on two action methods, for each HTTP request, a new instance of that TypeFilter will be created, the constructor will be called and dependencies will be injected (you can control the life cycle of dependencies using the Service Provider). In contrast, with ServiceFilter you decide if its Singleton or Scoped or Transient. If its Singleton then only one instance is created for all the requests.

KEY THING TO REMEMBER

It’s the filter type’s life cycle that we want to manage by using ServiceFilter and Service Provider. If the filter has dependencies, we already manage that using Service Provider like we normally do.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)