Exchanging a class instance between other classes in Castle Windsor

I am trying to find a better way to share an instance of a class between two other classes that depend on it.

Let's say I have these classes:

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 {}

And for each instance, AI want the Done used cand Dto be the only instance D. When I create a new instance A(for example, using the factory), I want to c, and Dshared a new instance of the D.

So far, I figured that using a familiar lifestyle using 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();
}

, , factory. , D A, , . , , Three Container Calls.

- , Windsor . , D , .. A -> B -> C -> E -> F -> G -> D, D .

+3
1

D b c A, :

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, .

, , .

+3

Source: https://habr.com/ru/post/1788939/


All Articles