我知道我可以使用兒童容器。如果我有以下結構:如何從特定範圍隱藏組件註冊?
parent container
/ \
child container 1 child container 2
然後在「孩子1」我註冊的每個組件是從「孩子2」隱藏起來,而它們都可以從父容器使用共同的組件。我認爲這幾乎是我所需要的,但是我已經多次閱讀過,子容器是邪惡的,通常有更好的方法來實現相同的行爲。例如here剋日什托夫聲稱,該
Basically handler selectors and sub-resolvers give you all the power you need to handle scenarios where you would want to use child container instead. I think removing the child containers, and add some nicer support for contextual scoping of components would be the best solution.
是否有支持這一行動的例子?在閱讀相關文件後,我覺得我還處於黑暗中。我只是不明白如何使用自定義選擇器和子分解器來實現相同的行爲。
用例。我有以下組件的多個實例:我想用默認ArrayResolver
的幫助以解決
class Component
{
public Component(ILayer[] layers, ...)
{
...
}
}
。但是,對於Component
的每個實例,我只想注入一個特定的註冊圖層子集,這是專門爲此組件註冊的。如果我不使用子容器,登記可能會是這樣的:
container.Register(Component.For<ILayer>.ImplementedBy<LayerA>()
.Named("Component1_LayerA"));
container.Register(Component.For<ILayer>.ImplementedBy<LayerB>()
.Named("Component1_LayerB"));
//etc...
container.Register(Component.For<ILayer>.ImplementedBy<LayerB>()
.Named("Component2_LayerB"));
container.Register(Component.For<ILayer>.ImplementedBy<LayerC>()
.Named("Component2_LayerC"));
//etc...
conatiner.Register(Component.For<Component>.Named("Component1"));
conatiner.Register(Component.For<Component>.Named("Component2"));
現在,當我打電話container.Resolve<Component>("Component1")
我怎麼告訴溫莎只解決層,其名稱以「Component1_」開始?還是應該使用完全不同的方法?
這是[這些情況,使DI容器失敗IMO](http://criticalsoftwareblog.com/index.php/2015/08/23/why-di-containers-fail-with-復對象的圖形/)。我建議你看看[Pure DI](http://blog.ploeh.dk/2014/06/10/pure-di/)。 –