0

I have the following handler for my c# WebAPI project.

public class CustomLogHandler : DelegatingHandler
    {
        [Inject]
        public ILogRepository LogRepository { get; set; }

        ... some methods here   
     }

This handler is registered in my WebApiConfig.cs class.

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            ... some code here

            config.MessageHandlers.Add(new CustomLogHandler());
        }
}

Also my ILogRepository is registered in my NinjectWebCommon.cs class as my other repositories:

 kernel.Bind(typeof(ILogRepository)).To(typeof(Data.LogRepository));

The problem is that when I debug and the breakpoint hits my CustomLogHandler method, LogRepository instance is null.

Any clue?

VAAA
  • 14,531
  • 28
  • 130
  • 253
  • Register the handler with the kernel as well and then resolve the instance before adding it to the handler collection – Nkosi Jul 29 '18 at 18:07
  • Possible duplicate of [Inject dependency into DelegatingHandler](https://stackoverflow.com/questions/14756519/inject-dependency-into-delegatinghandler) – Blue Jul 29 '18 at 18:08

1 Answers1

0

I found a way that works great:

var service = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(ILogRepository)) as ILogRepository;

Hope this works for someone else.

Thanks

VAAA
  • 14,531
  • 28
  • 130
  • 253