24

ServiceFilter we must register in Startup.cs. TypeFilter is injected by Microsoft.Extensions.DependencyInjection.ObjectFactory, we don't need register that filter.

So when we should use ServiceFilter and when TypeFilter ?

Tseng
  • 52,202
  • 10
  • 166
  • 183
MrChudz
  • 489
  • 1
  • 4
  • 10

4 Answers4

19

According to Pro ASP.NET Core MVC 2 book. 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.

Yawar Murtaza
  • 3,110
  • 4
  • 28
  • 36
  • So, from what I understand, `ServiceFilter` should be used when we don't need to provide constructor parameters, and `TypeFilter` should be used when we do? That way, if we never need to provide parameters, we'll avoid needlessly creating a new instance of `TypeFilter` for each request? – Lukas Aug 03 '20 at 14:51
12

Ok, so documentation:

  • A ServiceFilter retrieves an instance of the filter from DI. Using ServiceFilter without registering the filter type results in an exception.

  • TypeFilterAttribute is very similar to ServiceFilterAttribute (and also implements IFilterFactory), but its type is not resolved directly from the DI container. Instead, it instantiates the type by using Microsoft.Extensions.DependencyInjection.ObjectFactory.

Because of this difference, types that are referenced using the TypeFilterAttribute do not need to be registered with the container first (but they will still have their dependencies fulfilled by the container).

Community
  • 1
  • 1
Set
  • 40,147
  • 18
  • 114
  • 133
  • 3
    I know that - but I still don't see when I should use ServiceFilter and when I should use Typefilter. – MrChudz Apr 28 '17 at 05:34
  • 2
    So what is exactly `Microsoft.Extensions.DependencyInjection.ObjectFactory`? How does this work if you don't register it with the container? – gyozo kudor Jun 15 '17 at 12:27
11

Both ServiceFilter and TypeFilter are constructed using dependency injection.

According to this the TypeFilter is instantiated using Microsoft.Extensions.DependencyInjection.ObjectFactory which ultimately allows you to provide constructor parameters yourself (You can see an Arguments parameter in its constructor). It also resolves the ones you don't provide.

So you can do something like this:

public class AttachMetadataAttribute : Attribute, IAsyncActionFilter
{
    public AttachMetadataAttribute(SomeType someValue, ISomeService service)
        {
        }
}

And you can use that like this:

[TypeFilter(typeof(AttachMetadataAttribute),
    IsReusable = true,
    Order = 10,
    Arguments = new object[] { someValue})]

So here the the first parameter (someValue) is provided by you and the service gets injected by the container.

Note: Careful about IsReusable. If it's set to true the injected service is only created once.

Alireza
  • 111
  • 1
  • 4
0

If your filter has dependencies that you need to resolve from the container, then use TypeFilterAttribute. It allows you to perform constructor injection.

grokky
  • 6,461
  • 12
  • 47
  • 78