本文介绍了Kernel.Get< T>()线程安全+良好的模式可以在组件之间共享内核的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kernel.Get()线程安全吗?我的目标是在我所有的componenet中共享我的内核实例,并且它们可以很好地同时在不同线程上调用Kernel.Get().

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.

Kernel.Get()线程安全吗?

Is Kernel.Get() thread safe?

在位于不同dll中的所有应用程序组件之间共享应用程序内核的最佳模式是什么?如果可以的话,我不希望将工厂实例传递给应用程序的每个组件.

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.

推荐答案

获取是线程安全的,但是创建新的内核实例(ctor)当前不是线程安全的.

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:

  • 从应用程序的复合根目录开始(例如Program.Main,App.xaml,MVC控制器创建)
  • 如果您不知道创建复合根目录时需要多少个实例,请在工厂内部
  • 如果您不知道创建复合根目录时需要哪种实现,请在工厂内部
  • 如果由于内存/资源限制而需要延迟创建组件,请在工厂内部.

在所有情况下,将对内核的访问限制为复合根,并将工厂(类或Func<T>)注入需要在运行时创建对象的类.即使您不喜欢这样做,使那些工厂访问内核的最佳方法仍然是构造函数注入.或使用Func<T>( Ninject支持功能吗(自动生成的工厂)?).

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)? ).

这篇关于Kernel.Get&lt; T&gt;()线程安全+良好的模式可以在组件之间共享内核的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 20:35