Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
735 views
in Technique[技术] by (71.8m points)

asp.net mvc 4 - Share a Kernel between WebAPI and MVC

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...