Share a Kernel between WebAPI and MVC

為{幸葍}努か 提交于 2019-11-30 08:50:30

问题


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.


回答1:


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!




回答2:


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.



来源:https://stackoverflow.com/questions/21520417/share-a-kernel-between-webapi-and-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!