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

I am using the Ninject and Ninject.Web assemblies with a web form application. In the global.asax file, I specify the following bindings:

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

Then on my pages I just need to inherit them from Ninject.Web.PageBase. Then I can set the properties for the code behind the pages and put an attribute on it [inject].

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

This works great. But now I need to do some injection of the dependency in the Global.asax file. I need an instance IErrorLogEntryControllerin my Application_Errorevent. How can I solve this problem and use the specified binding for an abstract type?

protected void Application_Error(object sender, EventArgs e)
{
    IErrorLogEntryController = ???;
}
+3
source share
3 answers

Just do the same in your global class

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

NinjectHttpApplication .

+5

Ninject.Web - ASP.NET, ​​ KernelContainer . KernelContainer, -, Ninject.

, , .

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

Global.cs:

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

All Articles