64

I am trying to inject a service into my action filter but I am not getting the required service injected in the constructor. Here is what I have:

public class EnsureUserLoggedIn : ActionFilterAttribute
{
    private readonly ISessionService _sessionService;

    public EnsureUserLoggedIn()
    {
        // I was unable able to remove the default ctor 
        // because of compilation error while using the 
        // attribute in my controller
    }

    public EnsureUserLoggedIn(ISessionService sessionService)
    {
        _sessionService = sessionService;
    }

    public override void OnActionExecuting(ActionExecutingContext context)
    {
        // Problem: _sessionService is null here
        if (_sessionService.LoggedInUser == null)
        {
            context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            context.Result = new JsonResult("Unauthorized");
        }
    }
}

And I am decorating my controller like so:

[Route("api/issues"), EnsureUserLoggedIn]
public class IssueController : Controller
{
}

Startup.cs

services.AddScoped<ISessionService, SessionService>();
Nkosi
  • 191,971
  • 29
  • 311
  • 378
hyde
  • 2,383
  • 3
  • 19
  • 45
  • Attributes decorations allows only constant values. I guess you should resolve your service in the default constructor. – T-moty Mar 20 '16 at 01:15
  • I am not sure how that is possible in this scenario. – hyde Mar 20 '16 at 01:16
  • 1
    Take a look here, i guess you only need a [decorator](https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=98) – T-moty Mar 20 '16 at 01:34
  • I have a working solution for this - I'm updating it for ASP.NET Core. Hopefully I'll have something in a few minutes. – Scott Hannen Mar 20 '16 at 01:34
  • 3
    Instead of attempting to inject services into attributes, write [passive attributes](http://blog.ploeh.dk/2014/06/13/passive-attributes). – Mark Seemann Mar 20 '16 at 09:37
  • 3
    You shouldn't implement your own filter or authorization attributes for authorization/policy. That's what the policy builder and Policy property of `AuthoirzeAttribute`. See this answer from an ASP.NET Developer responsible for the security parts of ASP.NET Core http://stackoverflow.com/a/31465227/455493 – Tseng Mar 20 '16 at 11:37

6 Answers6

74

Using these articles as reference:

ASP.NET Core Action Filters

Action filters, service filters and type filters in ASP.NET 5 and MVC 6

Using the filter as a ServiceFilter

Because the filter will be used as a ServiceType, it needs to be registered with the framework IoC. If the action filters were used directly, this would not be required.

Startup.cs

public void ConfigureServices(IServiceCollection services) {
    services.AddMvc();

    services.AddScoped<ISessionService, SessionService>();
    services.AddScoped<EnsureUserLoggedIn>();

    ...
}

Custom filters are added to the MVC controller method and the controller class using the ServiceFilter attribute like so:

[ServiceFilter(typeof(EnsureUserLoggedIn))]
[Route("api/issues")]
public class IssueController : Controller {
    // GET: api/issues
    [HttpGet]
    [ServiceFilter(typeof(EnsureUserLoggedIn))]
    public IEnumerable<string> Get(){...}
}

There were other examples of

  • Using the filter as a global filter

  • Using the filter with base controllers

  • Using the filter with an order

Take a look, give them a try and see if that resolves your issue.

Hope this helps.

Nkosi
  • 191,971
  • 29
  • 311
  • 378
  • 1
    Yup, this worked. I was unfamiliar with the ServiceFilter attribute before. That was the piece missing in my code. Thank you. – hyde Mar 20 '16 at 02:47
  • 1
    You shouldn't do authorization policy checks this way, it's not the way in was intended to. You are supposed to use i.e. Cookie Authorization or some other authorization type (jwt for example) and then use `AuthorizeAttribute` with policies you set up on application startup. Check my comment above – Tseng Mar 20 '16 at 11:39
  • Interestingly a global filter does not seem to a allow for DI, see: https://github.com/damienbod/AspNet5Filters/blob/e2949743baa529a2e645abe66116c82543d10e03/src/AspNet5Filters/Startup.cs#L37 - the author of the blogs actually hard-wires dependencies himself there. – Stefan Hendriks May 18 '16 at 09:18
  • Found a blog that actually covers Global filters + dependency injection: http://weblogs.asp.net/ricardoperes/asp-net-core-inversion-of-control-and-dependency-injection – Stefan Hendriks May 18 '16 at 09:20
  • 4
    How does this work if you need to specify properties on the attribute? – Jeremy Holovacs Jan 12 '17 at 00:13
32

Global filters

You need to implement IFilterFactory:

public class AuthorizationFilterFactory : IFilterFactory
{
    public bool IsReusable => false;

    public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
    {
        // manually find and inject necessary dependencies.
        var context = (IMyContext)serviceProvider.GetService(typeof(IMyContext));
        return new AuthorizationFilter(context);
    }
}

In Startup class instead of registering an actual filter you register your filter factory:

services.AddMvc(options =>
{
    options.Filters.Add(new AuthorizationFilterFactory());
});
Andrei
  • 36,642
  • 31
  • 139
  • 196
32

One more way for resolving this problem. You can get your service via Context as in the following code:

public override void OnActionExecuting(ActionExecutingContext context)
{
    _sessionService = context.HttpContext.RequestServices.GetService<ISessionService>();
    if (_sessionService.LoggedInUser == null)
    {
        context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
        context.Result = new JsonResult("Unauthorized");
    }
}

Please note that you have to register this service in Startup.cs

services.AddTransient<ISessionService, SessionService>();
Igor Valikovsky
  • 536
  • 5
  • 5
  • I can't use GetService . It tells me to use Microsoft.Extensions.DependencyInjection.ServerProviderServiceExtensions.GetService, but I can't seem to find that available. – SventoryMang Aug 24 '17 at 22:46
  • 2
    This looks like the best solution for me with this small adjustment: var service = context.HttpContext.RequestServices.GetService(typeof(IMyService)) as IMyService; – BrokeMyLegBiking Dec 21 '17 at 21:13
  • 3
    This may work but it is using Service Locator pattern which are sometimes considered anti pattern – Anjani Mar 28 '18 at 07:24
11

Example

private ILoginService _loginService;

public override void OnActionExecuting(ActionExecutingContext context)
        {
            _loginService = (ILoginService)context.HttpContext.RequestServices.GetService(typeof(ILoginService));
        }

Hope it helps.

Bukunmi
  • 1,718
  • 12
  • 10
  • 2
    Simple sample but straight forward. The right one that I was looking for. By using (T)context.HttpContext.RequestServices.GetService(typeof(T)) it resolves the dependency. Good job. – Jerameel Resco Sep 04 '20 at 14:59
9

After reading this article ASP.NET Core - Real-World ASP.NET Core MVC Filters (Aug 2016) I implemented it like this:

In Starup.cs / ConfigureServices:

services.AddScoped<MyService>();

In MyFilterAttribute.cs:

public class MyFilterAttribute : TypeFilterAttribute
{        
    public MyFilterAttribute() : base(typeof (MyFilterAttributeImpl))
    {

    }

    private class MyFilterAttributeImpl : IActionFilter
    {
        private readonly MyService _sv;

        public MyFilterAttributeImpl(MyService sv)
        {
            _sv = sv;
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {                
            _sv.MyServiceMethod1();
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            _sv.MyServiceMethod2();
        }
    }
}

In MyFooController.cs :

[MyFilter]
public IActionResult MyAction()
{
}

Edit: Passing arguments like [MyFilter("Something")] can be done using the Arguments property of the TypeFilterAttribute class: How do I add a parameter to an action filter in asp.net? (rboe's code also shows how to inject things (the same way))

Community
  • 1
  • 1
A.J.Bauer
  • 2,383
  • 22
  • 29
1

While the question implicitly refers to "filters via attributes", it is still worth highlighting that adding filters "globally by type" supports DI out-of-the-box:

[For global filters added by type] any constructor dependencies will be populated by dependency injection (DI). Adding a filter by type is equivalent to filters.Add(new TypeFilterAttribute(typeof(MyFilter))). https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.2#dependency-injection

With regards to attribute-based filters:

Filters that are implemented as attributes and added directly to controller classes or action methods cannot have constructor dependencies provided by dependency injection (DI). This is because attributes must have their constructor parameters supplied where they're applied. This is a limitation of how attributes work. https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-2.2#dependency-injection

However, as mentioned in the previous answers to the OP, there are ways of indirection that can be used to achieve DI. For the sake of completeness, here are the links to the official docs:

B12Toaster
  • 8,944
  • 5
  • 48
  • 48