I've got a simple MVC4 site which uses ASP.NET webAPI and also MVC pages.

I'd like to use Ninject DI for both controller types but I'm wondering how this can be done?

I've got Ninject DI working for WebAPI, but now not sure how to share the same Kernel elegantly.

Should I be using some sort of Kernel singleton which both Dependency Resolvers can refer to?

Anyone had any experience with this?

Cheers.

有帮助吗?

解决方案

You should use the same IKernel instance for a single application-level composition root, may be WebApi or MVC controllers.

If you are using Ninject.MVC3 package:

When the kernel is initialized in NinjectWebCommon.cs inside your App_Start folder, you already have access to it. For MVC controllers, you don't need to do anything else for Ninject DI to work.

But for WebAPI controllers, you need to use a DependencyResolver to inject dependencies into your controllers. Using this implementation for this resolver, you then set it to be the resolver for all your WebAPI controllers like this:

  1. Bind the NinjectDependencyResolver to self (optional), inside RegisterServices in NinjectWebCommon.cs:

    kernel.Bind<NinjectDependencyResolver>().ToSelf();
    
  2. Set the WepAPI configuration to use your Resolver, usually inside WebApiConfig.cs:

    public static void Register(HttpConfiguration config)
    {
        //Other initialization code
        config.DependencyResolver = (new   Bootstrapper()).Kernel.Get<NinjectDependencyResolver>();
    }
    

This will fit your scenario for all controllers sharing the same IKernel.

Hope that helps!

其他提示

Yes, you are right. There should be one kernel/ container for an application, because this will eleminate possible mistakes in the future.In case of multiple kernels, you may register an interface in a kernel, and then try to resolve it using another kernel, and the program crashes.Only After spending time debugging, you find out what was wrong,etc.

In addition, using a single kernel, you wouldn't have to register a same implementation multiple times.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top