使用现有的自定义库从HttpHandler访问Ninject Kernel.Get() [英] Accessing Ninject Kernel.Get() from HttpHandler with existing custom base

查看:127
本文介绍了使用现有的自定义库从HttpHandler访问Ninject Kernel.Get()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Ninject 2.2.0.0的ASP.Net Webforms应用程序

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

我有一个从Microsoft.Web.ImageHandler类继承的HTTPHandler.

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.

因为我不能从Ninject.Web.HttpHandlerBase继承,我以为我只是将内核公开为Global.asax类的一个属性...

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;
    }

并使用kernel.Get方法获取服务.

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

更新: 我设法通过修改Global.Kernel属性来解决此问题,但是现在我进入了反模式领土 ...

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..

推荐答案

这是使用 Service-Locator反模式.它将起作用,但是您会失去IoC的灵活性,并在所有难以测试的地方添加依赖项.

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.

这个简单的答案是您可以将"KernelContainer.Inject(this)"添加到HttpHandler中.或者,您可以创建一个自定义模块(或修改现有的Ninject.Web模块)以在处理程序执行之前进行注入.

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.

这篇关于使用现有的自定义库从HttpHandler访问Ninject Kernel.Get()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆