Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection for ASP.NET WebAPI ActionFilters using Ninject not working

I am attempting to set up DI on ActionFilters in ASP.NET WebAPI using Ninject. I followed the instructions here: https://github.com/ninject/Ninject.Web.WebApi/wiki/Dependency-injection-for-filters

I create my ActionFilter like so:

public class ApiAuthorizeFilter : AbstractActionFilter
{
    private readonly IValidateApiTokenService _validateApiTokenService;

    public ApiAuthorizeFilter(IValidateApiTokenService validateApiTokenService)
    {
        _validateApiTokenService = validateApiTokenService;
    }

    public override bool AllowMultiple => true;

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
    }
}

I configured like so:

kernel.BindHttpFilter<ApiAuthorizeFilter>(FilterScope.Controller);

My understanding based on the info at the above link is that the ActionFilter should then run for all Actions in all WebAPI controllers. However, I've set breakpoints at both overridden methods in the filter and it never gets hit. I have set a breakpoint at the configuration and can confirm that it is being executed.

What am I missing? I need this ActionFilter to run on all Actions in every ApiController in my project.

like image 728
Mike Cole Avatar asked May 15 '16 16:05

Mike Cole


2 Answers

in your Startup Class

public void Configuration(IAppBuilder app)
{    
    var kernel = new StandardKernel();
    // register IValidateApiTokenService
    var config = new HttpConfiguration();
    config.Filters.Add(new ApiAuthorizeFilter(kernel.Get<IValidateApiTokenService>());
}
like image 172
swissarmykirpan Avatar answered Oct 24 '22 00:10

swissarmykirpan


The reason it doesn't work per say is because ActionFilters (or any filters for that matter) are created as singletons by the runtime (one instance forever on the app context) and in general any DI container has problems wiring up a object's transient and or disposable dependencies if that object is a singleton.

One solution to your problem would be to use the built in service locator like so: DependencyResolver.Current.GetService(typeof(IValidateApiTokenService));

I don't personally use Ninject for my DI needs but if the above doesn't work it probably needs some wiring up in the DI startup or use a integration package like this one: https://github.com/ninject/ninject.web.mvc/wiki/MVC3

like image 34
Denis Susan Avatar answered Oct 24 '22 00:10

Denis Susan