在温莎城堡其他类之间共享类的实例 [英] Sharing instance of class between other classes in Castle Windsor
问题描述
我试图找出最好的方法两个依赖于它的其他类之间共享一个类的实例。
I'm trying to figure out the best way to share an instance of a class between two other classes that depend on it.
说我有这些类:
class A
{
public A(B b, C c) {}
}
class B
{
public B(IDFactory factory) {}
}
class C
{
public C(IDFactory factory) {}
}
interface IDFactory
{
D GetD();
}
class D {}
和为 A
,我想每个实例的 D
c所用由
和 D
是 D
的单个实例。当我创建 A
的新实例(比如使用工厂),我想 C
和ð
来分享的新的的D实例。
And for each instance of A
, I want the D
used by c
and d
to be a single instance of D
. When I create a new instance of A
(say using a factory), I want c
and d
to share a new instance of D.
到目前为止,我已经想通了使用使用环境自定义的生活方式(使用这个一>酷库)可能是最好的办法。所以,我会做这样的事情:
So far I've figured that using a custom lifestyle that uses a context (using this cool library) might be the best approach. So I would do something like this:
WindsorContainer container = new WindsorContainer();
[.. standard container registration stuff ..]
container.Register(Component.For<D>().LifeStyle.Custom<ContextualLifestyle>());
IAFactory factory = container.Resolve<IAFactory>();
using (new ContainerContext(container))
{
A a = factory.GetA();
}
现在的问题,我与这是我在那里我用的是工厂的点定义背景。理想的情况是这样的概念, D
是半短暂的,应该有每个 A
的实例中的一个实例,将在配置当我登记我的所有类型的容器。另一个问题是,上下文所需要的容器本身,这违背了三个容器调用模式的实例。
Now the problem I have with this is that I have to define the context at the point where I use the factory. Ideally this concept that D
is semi-transient and should have a single instance per instance of A
would be configured in the container when I register all my types. Another issue is that the context needs an instance of the container itself, which goes against the Three Container Calls pattern.
任何人都可以提出设置这样的事情了,无论是使用温莎或有更好的体系结构的更好的方法。还铭记使D可能是相当深的层次结构类,即 A - &GT;乙 - &GT; C - &GT; Ë - &GT;的F - &GT;摹 - &GT; ð
,我想避免将 D
一路下滑树。
Can anyone suggest a better way of setting this kind of thing up, either using Windsor or with a better architecture. Also bearing in mind that D might be quite deep in the class heirarchy i.e. A -> B -> C -> E -> F -> G -> D
and I want to avoid passing D
all the way down the tree.
推荐答案
如果你想分享A的B和C之间的依赖关系D的同一个实例,那么这应该是足够的:
If you want to share the same instance of D between b and c dependencies of A, then this should be enough:
class A
{
public A(B b, C c) { }
}
class B
{
public B(D d) { }
}
class C
{
public C(D d) { }
}
...
container.Register(Component.For<D>().LifeStyle.Custom<ContextualLifestyle>());
A a = container.Resolve<A>();
如果您IAFactory使用container.Resolve实现,你可以用这个来代替直接调用。
If your IAFactory is implemented using container.Resolve you can use that instead of a direct call.
另外,如果你只是一个解析顶级组件,可以省略的背景下明确的创作。
Also, if you are only resolving one "top level" component, you can omit the explicit creation of the context.
这篇关于在温莎城堡其他类之间共享类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!