Accessing Ninject Kernel.Get() from HttpHandler with existing custom base

对着背影说爱祢 提交于 2019-12-07 22:44:33

问题


I have an ASP.Net webforms app, that uses Ninject 2.2.0.0

I have a HTTPHandler that inherits from the Microsoft.Web.ImageHandler class.

Within it i need to access an instance of a service class that i created.

because i cannot inherit from Ninject.Web.HttpHandlerBase i thought i would just expose the Kernel as a property on the Global.asax class...

protected override IKernel CreateKernel()
    {
        IKernel kernel = new StandardKernel(new DefaultModule());

        var sms = kernel.Get<SiteMapService>();
        SiteMapSvc = sms;
        Kernel = kernel;
        return kernel;

    }

    public IKernel Kernel
    {
        get; set;
    }

and use the kernel.Get method to obtain the service..

var global = (Global) HttpContext.Current.ApplicationInstance;

var service = global.Kernel.Get<PhotoService>();

This fails with the following...

   [ArgumentNullException: Cannot be null
Parameter name: root]
   Ninject.ResolutionExtensions.GetResolutionIterator(IResolutionRoot root, Type service, Func`2 constraint, IEnumerable`1 parameters, Boolean isOptional, Boolean isUnique) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:258
   Ninject.ResolutionExtensions.Get(IResolutionRoot root, Type service, IParameter[] parameters) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:151
   Thumb.GenerateImage(NameValueCollection parameters) in \Thumb.ashx.cs:40

UPDATE: I managed to fix this by modifying the Global.Kernel property to this, but now im getting into anti pattern territory...

public IKernel Kernel
    {
        get { return this.CreateKernel(); }
    }

Will now read up and see what this means..


回答1:


This is using the Service-Locator anti-pattern. It will work, but you lose the flexibility of IoC and add a dependency everywhere that is difficult to test.

This simple answer is that you can add "KernelContainer.Inject(this)" to your HttpHandler. Or you can create a custom module (or modify the existing Ninject.Web one) to do injection before handler execution.



来源:https://stackoverflow.com/questions/5523130/accessing-ninject-kernel-get-from-httphandler-with-existing-custom-base

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!