How do you resolve a Ninject dependency in the glo

2019-02-19 00:38发布

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

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

3条回答
成全新的幸福
2楼-- · 2019-02-19 01:23

Simply do the same thing in your Global class

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

NinjectHttpApplication injects itself after the kernel is created.

查看更多
太酷不给撩
3楼-- · 2019-02-19 01:26

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>();
}
查看更多
ら.Afraid
4楼-- · 2019-02-19 01:28
    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);


    }
查看更多
登录 后发表回答