How to store Ninject Kernel in an ASP.NET Application?

落花浮王杯 提交于 2020-01-02 10:02:43

问题


I'm really confused about small, partial, one-file examples where there's a Ninject kernel everywhere without showing how to really get to that kernel in the application.

(1) Should we instantiate one Kernel and keep it in "static" context? Or should we instantiate a different one on every request (*in Application_BeginRequest*)

(2) If it is "kernel per request", then why Initialize() method of the NinjectWebCommon.cs (gets when you install the NuGet package) is called on Application_Start since it calls bootstrapper.Initialize(CreateKernel) - NinjectWebCommon.cs

(3) If it is "one global static kernel" then the "InRequestScope()" doesn't work. It executes the following code and that returns null because at ApplicationStart() time there's no request.

kernel.Components.GetAll<INinjectHttpApplicationPlugin>()
  .Select(c => c.RequestScope)
  .FirstOrDefault(s => s != null);

(4) Again, if it is "kernel per request", where will we save the kernel? HttpContext.Current? Then what is meaning of using InRequestScope() if I'm going to use HttpContext.Current anyway?


回答1:


(1) Should we instantiate one Kernel and keep it in "static" context? Or should we instantiate a different one on every request (*in Application_BeginRequest*)

One and single kernel.

(2) If it is "kernel per request", then why Initialize() method of the NinjectWebCommon.cs (gets when you install the NuGet package) is called on Application_Start since it calls bootstrapper.Initialize(CreateKernel) - NinjectWebCommon.cs

It isn't kernel per request.

(3) If it is "one global static kernel" then the "InRequestScope()" doesn't work. It executes the following code and that returns null because at ApplicationStart() time there's no request.

kernel.Components.GetAll() .Select(c => c.RequestScope) .FirstOrDefault(s => s != null);

That's perfectly normal. You cannot expect to get an instance from your kernel which you explicitly registered with InRequestScope outside of an HTTP Request.

(4) Again, if it is "kernel per request", where will we save the kernel? HttpContext.Current? Then what is meaning of using InRequestScope() if I'm going to use HttpContext.Current anyway?

Nowhere. You DON'T SAVE THE KERNEL. You use the kernel to configure your DI container only once at your application startup and then all dependencies are automatically injected. If you need the kernel somewhere in your application, other than the place where you configured your dependencies you have a serious design problem because you are no longer using Dependency Injection but Service Location which is an anti-pattern.



来源:https://stackoverflow.com/questions/17919314/how-to-store-ninject-kernel-in-an-asp-net-application

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