Share a Kernel between WebAPI and MVC
Asked Answered
S

2

3

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.

Sniffy answered 3/2, 2014 at 5:36 Comment(0)
B
3

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!

Boyles answered 3/2, 2014 at 13:18 Comment(1)
You have solution to your problem in related question #21158774Tuner
S
0

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.

Suture answered 3/2, 2014 at 5:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.