HttpHandler property injection using Ninject returning null

I have the following httphandler:

public class NewHandler : IHttpHandler { [Inject] public IFile FileReader { get; set; } public NewHandler() { } public void ProcessRequest(System.Web.HttpContext context) { .... var something = SomeMethod(FileReader); .... } public bool IsReusable { get { return true; } } } 

This is my Ninject module in Global.asax.

 internal class ServiceModule : NinjectModule { public override void Load() { Bind<IFile>().To<FileWrapper>().InSingletonScope(); } } 

Each time the handler fires, the FileReader is NULL. Am I missing something? Is it right to inject properties with Ninject?

thanks

+2
source share
1 answer

This is the correct way to inject properties with Ninject, but it will not work. You are probably using something like the NinjectMvcApplication class as the base class for your application, which handles dependency injection for controllers and all controllers can use (services, repositories). But HttpHandlers are not created by ControllerFactory , so nothing cares about introducing stuff.

There may be a better way to do this, but I used a service locator to resolve the dependency. See http://code.dortikum.net/2010/08/05/asp-net-mvc-di-with-common-service-locator-and-ninject/ .

UPDATE:

Try something like this:

 public class NewHandler : IHttpHandler { private readonly IFile _fileReader; public NewHandler() { _fileReader = ServiceLocator.Current.GetInstance<IFile>(); } public void ProcessRequest(System.Web.HttpContext context) { .... var something = SomeMethod(_fileReader); .... } public bool IsReusable { get { return true; } } } 
+3
source

Source: https://habr.com/ru/post/914886/


All Articles