Asp.net mvc 使用Ninject在MVC2中进行IHttphandler属性注入

Asp.net mvc 使用Ninject在MVC2中进行IHttphandler属性注入,asp.net-mvc,asp.net-mvc-2,dependency-injection,ninject,Asp.net Mvc,Asp.net Mvc 2,Dependency Injection,Ninject,我正在寻找一种在MVC中为iHttphandler进行属性注入的方法 对于webforms ninject,您可以从HttpHandlerBase继承 这不再有效,因为应用程序现在继承自Ninject.Web.Mvc.Ninject应用程序,而不是Ninject.Web.NinjectHttpApplication public abstract class HttpHandlerBase : IHttpHandler { public abstract void ProcessRequ

我正在寻找一种在MVC中为iHttphandler进行属性注入的方法

对于webforms ninject,您可以从HttpHandlerBase继承

这不再有效,因为应用程序现在继承自Ninject.Web.Mvc.Ninject应用程序,而不是Ninject.Web.NinjectHttpApplication

public abstract class HttpHandlerBase : IHttpHandler
{
    public abstract void ProcessRequest( HttpContext context );

    void IHttpHandler.ProcessRequest( HttpContext context )
    {
        Assembly ass = Assembly.Load("Ninject.Web.Mvc");
        Type type = ass.GetType("Ninject.Web.Mvc.KernelContainer");
        MethodInfo init = type.GetMethod("Inject", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(object) }, null );
        init.Invoke( null, new object[] {} );

        this.ProcessRequest( context );
    }
}
此应用程序为非PageBase、MasterPageBase或HttpHandlerBase的控制器注册类型

垃圾

这是一种可能与MvcHandler类一起实现的方式吗

下面的帖子是我得到的最接近答案


如果从源代码构建Ninject.Web.Mvc,请在Ninject.Web.Mvc命名空间中包含Ninject.Web的HttpHandlerBase类的副本

否则,您自己的HttpHandlerBase将需要调用
内核。在自身上注入
。内核引用可以通过应用范围或反射获得

HttpApplication.CreateKernel()中,将应用程序范围中的内核实例存储为“NinjectKernel”。然后添加以下内容作为IHttpHandler基类

public abstract class HttpHandlerBase : IHttpHandler
{
    public abstract void ProcessRequest( HttpContext context );

    void IHttpHandler.ProcessRequest( HttpContext context )
    {
        var kernel = (IKernel) context.Application["NinjectKernel"];
        kernel.Inject( this );

        this.ProcessRequest( context );
    }
}
反射方法不需要HttpApplication中的任何代码

public abstract class HttpHandlerBase : IHttpHandler
{
    public abstract void ProcessRequest( HttpContext context );

    void IHttpHandler.ProcessRequest( HttpContext context )
    {
        Assembly ass = Assembly.Load("Ninject.Web.Mvc");
        Type type = ass.GetType("Ninject.Web.Mvc.KernelContainer");
        MethodInfo init = type.GetMethod("Inject", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(object) }, null );
        init.Invoke( null, new object[] {} );

        this.ProcessRequest( context );
    }
}

为什么要将HttpHandler与MVC一起使用?我想你应该用一个合适的控制器/动作来代替它们。只是刚开始使用MVC,我觉得他们的方式会更适合MVC。我关心的是是否需要更新使用该处理程序的所有控制器(或控制器基类?)。它看起来不像在web.config中注册处理程序那样干净。如果处理程序在类库中,我可以在控制器中执行此操作吗?干杯谢谢你完美的回答。你知道为什么Ninject团队从MVC版本中删除了HttpHandlerBase吗?调整和重建源代码从来都不是一件理想的事情,因为您总是可以向系统中注入bug,并且您需要跟踪所有更改,并在更新到新版本时再次应用它们。是的,我是一个懒惰的程序员,但在一个好的方面,我希望lol!如果Ninject团队中有人在读这篇文章,为什么MVC会删除这项功能?他们有什么理由不把它添加到未来的版本中?再次为答案欢呼。史蒂夫