Is Kernel.Get<T>() threadsafe + good pattern to share the kernel among components

谁说我不能喝 提交于 2020-04-08 09:41:59

问题


Is Kernel.Get() threadsafe? My goal is share an instance of my kernel among all my componenets and they may all very well call Kernel.Get() at the same time on different threads.

Is Kernel.Get() thread safe?

What is the best pattern to share the application kernel among all application components which are sitting in different dll's? I prefer not to pass an instance of a factory to every component of my application if this makes sense.


回答1:


Get is threadsafe but creating new kernel instances (ctor) is currently not threadsafe.

Generally you should try to minimize your access to the kernel to an absolute minimum. Accessing the kernel form everywhere is a very bad design and makes your code much less reusable. See Service Locator Antipattern

The only situations where you access the kernel should be:

  • Once in the composite root of the application (e.g. Program.Main, App.xaml, MVC Controller creation)
  • Inside a factory if you don't know how many instances you need when the composite root is created
  • Inside a factory if you don't know which implementation is required when the composite root is created
  • Inside a factory if you need to create a component late due to memory/resource constraints.

In all cases limit the access to the kernel to the composite root and inject factories (class or Func<T>) to the classes where you need to create objects during runtime. The best way to give those factories access to the kernel is still constructor injection even if you do not prefer doing so. Or use Func<T> ( Does Ninject support Func (auto generated factory)? ).




回答2:


Yes, it is thread safe; The primary app I work on has a single kernel that serves a large SAAS app. So it gets pounded and it does just fine. We also have a multi-threaded page generator test suite that exposed a thread issue in Ninject last fall, but has been fixed and has been fine since then. So I know for sure that it's ok.

There are lots of different patterns for exposing the kernel. We use a ServiceLocator pattern (basically a static container for the container.)

For the different dll's. We have a NinjectModule in each dll that does it's own bindings and then the app does a assembly scan for NinjectModules at startup when it sets of the ServiceLocator.



来源:https://stackoverflow.com/questions/6338603/is-kernel-gett-threadsafe-good-pattern-to-share-the-kernel-among-component

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