Wednesday, February 22, 2017

ASP.NET Core–Injecting dependencies in an MVC ActionFilter

ASP.NET Core out-of-the-box supports dependency injection on the action filter level. You have to use constructor injection to inject your dependencies in the actionfilter:

However now it is no longer possible to simply add the action filter as an attribute on top of your controller or action method. This is because attributes must have their constructor parameters supplied where they are applied. Instead you have to use one of the following attributes:

  • TypeFilterAttribute
  • ServiceFilterAttribute

The key difference is that TypeFilterAttribute will find and load the dependencies through DI, and inject them into your action filter.

The ServiceFilterAttribute on the other hand attempts to find the filter from the service collection. This means that you have to register your actionfilter first:

 

1 comment:

Whoever said...

In pre-core .NET MVC, it was mentioned

"Web API caches filter attribute instances indefinitely per action, effectively making them singletons. This makes them unsuited for dependency injection, since the attribute’s dependencies will be accidentally promoted to singleton as well, which can cause all sorts of concurrency issues."

Do we know if this is still the case? Thanks