如何在ASP.NET中的全局文件中解决Ninject依赖关系? [英] How do you resolve a Ninject dependency in the global file in ASP.NET?

查看:167
本文介绍了如何在ASP.NET中的全局文件中解决Ninject依赖关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the Ninject and Ninject.Web assemblies with a web forms application. In the global.asax file I specify the bindings like so:

public class Global : NinjectHttpApplication
{
    protected override IKernel CreateKernel()
    {
        IKernel kernel = new StandardKernel();

        // Vendor Briefs. 
        kernel.Bind<IVendorBriefRepository>().To<VendorBriefRepository>().InRequestScope();
        kernel.Bind<IVendorBriefController>().To<VendorBriefController>().InRequestScope();

        // Search Services. 
        kernel.Bind<ISearchServicesController>().To<SearchServicesController>().InRequestScope();
        kernel.Bind<ISearchServicesRepository>().To<SearchServicesRepository>().InRequestScope();

        // Error Logging
        kernel.Bind<IErrorLogEntryController>().To<ErrorLogEntryController>().InRequestScope();
        kernel.Bind<IErrorLogEntryRepository>().To<ErrorLogEntryRepository>().InRequestScope();


        return kernel;
    }
}

然后在我的网页上,我只需要让他们继承来自 Ninject.Web.PageBase 。然后我可以在页面后面的代码上设置属性,并将 [inject] 属性放在其上。

Then in my pages I simply have to make them inherit from Ninject.Web.PageBase. Then I can set up properties on the code behind pages and put the [inject] attribute over it.

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

这很好用。但是现在我需要在Global.asax文件本身做一些依赖注入。我的 Application_Error 事件中需要一个 IErrorLogEntryController 的实例。如何解决这个问题,并使用我指定的绑定的抽象类型?

This works great. But now I need to do some dependency injection in the Global.asax file itself. I need an instance of IErrorLogEntryController in my Application_Error event. How do I resolve this and use my specified binding for the abstract type?

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


推荐答案

只要做同样的事情您的全球课程

Simply do the same thing in your Global class

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

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

NinjectHttpApplication injects itself after the kernel is created.

这篇关于如何在ASP.NET中的全局文件中解决Ninject依赖关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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