0

I using:

using Microsoft.Extensions.DependencyInjection;

When I try to create new ActionFilter i need have access to other services so I try write standard constructor inject but when my costructor have parameters I have to write something like that:

[OAuthFilter(serviceToInject)]

I cant to that becouse action filters can't have this kind of parameters.

What I should do? Action filters can't have a inject constructors?

donex93
  • 513
  • 2
  • 5
  • 16
  • @Steven that is for ASP.NET MVC or ASP.NET 4, this is ASP.NET Core – Camilo Terevinto Feb 21 '17 at 10:58
  • @CamiloTerevinto: The answer is still the same: Make your attributes either [passive](http://blog.ploeh.dk/2014/06/13/passive-attributes/) or [Humble objects](http://xunitpatterns.com/Humble%20Object.html). – Steven Feb 21 '17 at 11:26

1 Answers1

1

You can use the TypeFilterAttribute:

[TypeFilter(typeof(OAuthFilter))]
public class HomeController : Controller
{
}

This will instantiate your filter and get any needed components through dependency injection. Another alternative is the ServiceFilterAttribute:

[ServiceFilter(typeof(OAuthFilter))]
public class HomeController : Controller
{
}

But this requires that you add your filter to the service collection:

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<OAuthFilter>();
}
juunas
  • 54,244
  • 13
  • 113
  • 149