Search code examples
c#castle-windsor

Injecting Dependencies using Castle Windsor


Consider I have one interface.

interface Interface<A> {}  

Now I have 2 classes which implement this interface:

class ClassOne<A>: I<A> {}
class ClassTwo<A>: I<A> {}  

Now I want to use these 2 classes in a third class.

class child
{
    child(Interface<A> objCA,Interface<A> objCB)
    {}
}  

I am not able to inject the dependency for child class using Castle Windsor. Even if I inject it, it is passing only one object to all of them. So how can I resolve this scenario using Castle Windsor?


Solution

  • You can do this by using Castle Windsor collection/array/list resolvers.

    Take a look: https://github.com/castleproject/Windsor/blob/master/docs/resolvers.md

    This way you will be able to get the same behavior with slightly different syntax.

    Configure the container like this:

    container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel));
    

    Register CA and CB like this:

    container.Register(Component.For<IA>().ImplementedBy<CA>());
    container.Register(Component.For<IA>().ImplementedBy<CB>());
    

    and change your class to:

    class child
    {
        child(IEnumerable<IA> objs)
        {}
    }