Inject dependency into DelegatingHandler

10,888

Solution 1

DelegatingHandlers are only initialized once in Web API, at application start.

This is a known issue/design feature of Web API (I presume for performance reasons) - see the bug report here http://aspnetwebstack.codeplex.com/workitem/62.

Using a constructor initialization like you suggested yourself, would only work if you have singleton-type dependencies (that' why you logger works). Regardless, if you want to delegate the resolution to Web API DependencyResolver you have to use GetDependencyScope(), which can be called off the HttpRequestMessage, as a workaround.

I posted a walkthrough on doing that with Ninject a while ago. You should use this approach to resolve your deendency, because with your current solution you have coupled Ninject & your handler, which is far from desired.

Solution 2

I am using this:

 protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
 {
    var service = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IFooService)) as IFooService;
    // Other stuff
 }

Solution 3

I think what you need is this.

It's the Ninject dependency resolver for MVC. Then I believe you need to use:

GlobalConfiguration.Configuration.ServiceResolver.SetResolver()

And pass in the NInject dependency resolver.

Share:
10,888
Jos Vinke
Author by

Jos Vinke

nl.linkedin.com/in/jvinke

Updated on June 04, 2022

Comments

  • Jos Vinke
    Jos Vinke about 2 years

    I am new to dependency injection, but happy with Ninject and Ninject.Extensions.Logging to [Inject] my ILogger wherever i need it.

    However some DelegatingHandlers are spoiling all the fun.

    public class HttpsHandler : DelegatingHandler
    {
        [Inject]
        public ILogger Logger { get; set; }
    
        protected override Task<HttpResponseMessage> SendAsync(
                HttpRequestMessage request, CancellationToken cancellationToken)
            {
                if (!string.Equals(request.RequestUri.Scheme, "https", StringComparison.OrdinalIgnoreCase))
                {
                    Logger.Info(String.Format("{0}: is using HTTP", request.RemoteAddress());
                    return
                        Task.Factory.StartNew(
                            () =>
                            new HttpResponseMessage(HttpStatusCode.BadRequest)
                            {
                                Content = new StringContent("HTTPS Required")
                            });
                }
    
                return base.SendAsync(request, cancellationToken);
            }
     }
    

    Could anyone point me in the right direction on how to Inject Ninject.Extensions.Logger.Nlog2 into Ilogger inside the delegatinghandlers?

    Update

    I think Pete got me in the right direction in the comments (thanks!). I added the following constructor to the HttpsHandler:

    public HttpsHandler()
            {
                var kernel = new StandardKernel();
    
                var logfactory = kernel.Get<ILoggerFactory>();
                this.Logger = logfactory.GetCurrentClassLogger();
            }
    

    and now i've got the Logger working!

    My only question left, is this the right way to do it, or is it a anti-pattern?

  • Jos Vinke
    Jos Vinke over 11 years
    I have tried your solution, but I can't really figure it out. I'm using Asp.Net WebApi (updated tags) and ServiceResolver doesn't exist, it is DependencyResolver in Web Api. I tried a custom DependencyResolver but without any luck. Any other suggestions? Thanks anyway +1 for the help so far.
  • Pete
    Pete over 11 years
    Ah, don't really know, then. Your initial tag said asp.net MVC, so that was the solution I knew. Sorry. maybe someone else can help you.
  • Jos Vinke
    Jos Vinke over 11 years
    Yeah I tagged it with MVC because it's a MVC delegatinghandler and not a HTTP delegatinghandler. Like HTTP Controllers vs MVC Controllers which are both used in a Web Api application. Confuse them and you're up for a fun time solving things. That's why I tagged MVC but sorry for the inconvenience and thanks for the time spend :)
  • Jos Vinke
    Jos Vinke over 11 years
    Thanks I think i've got your solution working (nice blog!), I just can't verify because I get a null reference when the dependency is resolved in the GetService method. ( at Ninject.Extensions.Logging.LoggerFactoryBase.GetLogger(ICont‌​ext context) in c:\Projects\Ninject\ninject.extensions.logging\src\Ninject.E‌​xtensions.Logging\Lo‌​ggerFactoryBase.cs:l‌​ine 61). Could you confirm this is a bug in Ninject.Extensions.Logging or did I do something wrong?
  • Filip W
    Filip W over 11 years
    Well GetService is simply resolving from kernel.Get. SO you need to register the logger at application startup - something like kernel.Bind<X>().To<Y>(). I am not familiar with ninject.extensions.logging so not sure how exactly you do that, but it has to be defined at application startup, where you register all dependencies. GetDependencyScope() is simply a shortcut to resolve something from your Ninject kernel, without explicitly specifying it (without coupling yourself to the Ninject kernel, since you can easily change DI provider and this code will still work).
  • Jos Vinke
    Jos Vinke over 11 years
    The service is registered and it also gets to the LoggerFactory (see the trace) also if i register it (again) i get a exception that multiple ILoggers are registered. For now I'll mark your answer as accepted and i'll give it a shot with another dependency when i've got a little more time on my hands. Thanks for the help.
  • Jos Vinke
    Jos Vinke over 11 years
    I just wanted to let you know that I had another scenario where this came really handy and that your solution worked great, thanks!
  • Ecyrb
    Ecyrb over 5 years
    I was trying to use this from within my own NuGet package that didn't know about GlobalConfiguration. I was able to find it in the Microsoft.AspNet.WebApi.WebHost package.