如何解决ASP.NET中全局文件中的Ninject依赖项?

我正在使用带有Web表单应用程序的Ninject和Ninject.Web程序集。 在global.asax文件中,我指定绑定,如下所示:

public class Global : NinjectHttpApplication { protected override IKernel CreateKernel() { IKernel kernel = new StandardKernel(); // Vendor Briefs. kernel.Bind().To().InRequestScope(); kernel.Bind().To().InRequestScope(); // Search Services. kernel.Bind().To().InRequestScope(); kernel.Bind().To().InRequestScope(); // Error Logging kernel.Bind().To().InRequestScope(); kernel.Bind().To().InRequestScope(); return kernel; } } 

然后在我的页面中,我只需要让它们inheritance自Ninject.Web.PageBase 。 然后我可以在页面后面的代码上设置属性并将[inject]属性放在它上面。

 [inject] public IVendorBriefController vendorBriefController { get; set; } 

这很好用。 但是现在我需要在Global.asax文件本身中进行一些dependency injection。 我在Application_Error事件中需要一个IErrorLogEntryController实例。 如何解决此问题并将我指定的绑定用于抽象类型?

 protected void Application_Error(object sender, EventArgs e) { IErrorLogEntryController = ???; } 

只需在Global类中执行相同的操作即可

 [Inject] public IErrorLogEntryController ErrorLogEntryController { get; set; } 

NinjectHttpApplication在创建内核后注入自身。

如果您正在使用ASP.NET WebForms的Ninject.Web库 ,那么您应该能够从KernelContainer静态类中获取内核。 在这个库中,KernelContainer类似乎是使用Ninject的服务定位的起点。

拥有内核后,您可以获得所需的任何依赖项。

 protected void Application_Error(object sender, EventArgs e) { IErrorLogEntryController = KernelContainer.Kernel.Get(); } 
  protected void Application_Start() { HttpContext.Current.Application["UnityContainer"] = System.Web.Mvc.DependencyResolver.Current.GetService(typeof(EFUnitOfWork)); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }