开发者

How do you resolve a Ninject dependency in the global file in ASP.NET?

开发者 https://www.devze.com 2023-03-04 02:56 出处:网络
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:

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&g开发者_JAVA百科t;().To<SearchServicesRepository>().InRequestScope();

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


        return kernel;
    }
}

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

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 injects itself after the kernel is created.


If you're using the Ninject.Web library for ASP.NET WebForms, you should just be able to get the kernel from the KernelContainer static class. In this library, the KernelContainer class seems to be the starting point for service location using Ninject.

Once you have the kernel, you can get any dependency you need.

protected void Application_Error(object sender, EventArgs e)
{
    IErrorLogEntryController = KernelContainer.Kernel.Get<IErrorLogEntryController>();
}


Global.cs:

        HttpContext.Current.Application["UnityContainer"] = System.Web.Mvc.DependencyResolver.Current.GetService(typeof(EFUnitOfWork));
0

精彩评论

暂无评论...
验证码 换一张
取 消