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.
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:
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)? ).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With