HttpHandler Property Injection using Ninject returning null

前端 未结 2 1726
庸人自扰
庸人自扰 2020-12-18 15:00

I have the following httphandler:

public class NewHandler : IHttpHandler
{
    [Inject]
    public IFile FileReader
    {
        get;
        set;
    }

           


        
2条回答
  •  失恋的感觉
    2020-12-18 15:11

    This is the correct way to do property injection with Ninject, but it won't work. You are probably using something like NinjectMvcApplication class as a base class for you application, that handles dependency injection for controllers and everything controllers might use (services, repositories). But HttpHandlers are not instantiated by the ControllerFactory so nothing takes care of injecting stuff.

    Maybe there's better way to do it, but i used 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();
        }
    
        public void ProcessRequest(System.Web.HttpContext context)
        {
            ....
            var something = SomeMethod(_fileReader);
            ....
        }
    
        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
    

提交回复
热议问题