开发者

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

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\ResolutionEx开发者_如何学Ctensions.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..


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜