HttpHandler Property Injection using Ninject returning null

前端 未结 2 1716
庸人自扰
庸人自扰 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:17

    If you're using Ninject.Web.Common, you should have a NinjectWebCommon.cs in your app_start folder. That class instantiates a Bootstrapper class which contains a singleton instance of the Ninject kernel. That Ninject kernel is actually available everywhere in your app which means it's also available in HTTP factory classes.

    Here's how you can continue to use Ninject in more or less the same way you're using controllers:

    IHttpHandlerFactory is the composition root for IHttpHandler instances and as such you will need to create an implementation of this interface and add the necessary configuration elements to your web.config.

    MyHandlerFactory.cs:

    public class MyHandlerFactory : IHttpHandlerFactory
    {
        public bool IsReusable => false;
    
        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
           // the bootstrapper class uses the singleton pattern to share the Ninject Kernel across your web app's ApplicationDomain
           var kernel = new Bootstrapper().Kernel;
    
           // assuming you have only one IHttpHandler binding in your NinjectWebCommon.cs
           return kernel.Get();
        }
    
        public void ReleaseHandler(IHttpHandler handler)
        {
           // nothing to release
        }
    }
    

    Now, add the necessary config elements for your new handler factory...

    Web.config:

      
        
          
        
      
      
        
          
        
      
    

    Finally, add a binding for your IHttpHandler implementation...

    NinjectWebCommon.cs:

    private static void RegisterServices(IKernel kernel)
    {
        // other bindings you already have
    
        // the binding for your handler factory
        Bind().To();
    }
    

提交回复
热议问题