Search code examples
c#dependency-injectioninversion-of-controlcastle-windsorconstructor-injection

How to handle this DI resolving scenario?


So, lets assume I can draw in paint:

Horrible depiction of my problem

Say I have a class A which depends on objects B and C to be instanced, but C also depends on an instance of B, and I want this instance of B to be the same that I pass to A. How can I accomplish this?

Now, you probably didn't understand that at all either; so I'll go ahead and turn it into code:

public class A
{
    private readonly B b;
    private readonly C c;

    public A(B b, C c)
    {
        this.b = b;
        this.c = c;
    }
}

public class B
{    
}

public class C
{
    private readonly B b;

    public C(B b)
    {
        this.b = b;
    }
}

Without DI, I would resolve it like this:

var b = new B();
var c = new C(b);
var a = new A(b,c);

How can I accomplish something like this through DI, cleanly? What I want is pretty straightforward: use the same instance of B when instancing both C and A.

Forgot to mention I do want this in a per-web-request lifestyle, not singleton or transient.


Solution

  • According to the castle documentation, singleton behavior is already the default. Therefore, castle will create only one instance of B and pass it to both A and C.

    It's the cases where you don't want this that you should worry about. You need some extra configuration then, as described in the linked documentation.