如果您使用的是 Ninject.Web.Common,您的 app_start 文件夹中应该有一个 NinjectWebCommon.cs。该类实例化了一个包含 Ninject 内核的单例实例的 Bootstrapper 类。 Ninject 内核实际上在您的应用程序中随处可用,这意味着它也可以在 HTTP 工厂类中使用。
您可以通过以下方式继续使用 Ninject,其方式或多或少与您使用控制器的方式相同:
IHttpHandlerFactory 是 IHttpHandler 实例的组合根,因此您需要创建此接口的实现并将必要的配置元素添加到您的 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<IHttpHandler>();
}
public void ReleaseHandler(IHttpHandler handler)
{
// nothing to release
}
}
现在,为您的新处理程序工厂添加必要的配置元素...
Web.config:
<system.web>
<httpHandlers>
<add verb="GET" path="*.customThingImade" type="MyNamespace.MyHandlerFactory, MyAssemblyWhereIPutMyHandlerFactory, Version=1.0.0.0, Culture=neutral" />
</httpHandlers>
</system.web>
<system.webServer>
<handlers>
<add name="MyHandlerFactory" verb="GET" path="*.customThingImade" type="MyNamespace.MyHandlerFactory, MyAssemblyWhereIPutMyHandlerFactory, Version=1.0.0.0, Culture=neutral" preCondition="integratedMode" />
</handlers>
</system.webServer>
最后,为你的 IHttpHandler 实现添加一个绑定...
NinjectWebCommon.cs:
private static void RegisterServices(IKernel kernel)
{
// other bindings you already have
// the binding for your handler factory
Bind<IHttpHandler>().To<NewHandler>();
}