Search code examples
c#.netdependency-injectioninversion-of-controlcastle-windsor

Castle Windsor - How to create an installer to deal with multi level dependency structures


I have a case where several different classes inherit from the same interface. Additionally, sometimes a class that inherits from the interface, also takes it as a dependency.

My solution looks like this:

InterfaceAssembly
    -IGetData<T>

DataAssembly
    -Repository.CustomerRepository : IGetData<Customer>
    -Repository.ProductRepository : IGetData<Product>
    -Cache.CustomerCache : IGetData<Customer>
    -Cache.ProductCache : IGetData<Product>

I would like to make an installer that prioritizes the Cache namespace over Repository name space. However, in the case of CustomerCache, it both implements, and has a dependency on IGetData<Customer>. CustomerCache should be injected with CustomerRepository to satisfy this dependency.

Is there a easy way to deal with this type of situation with Castle Windsor? Will I have to take special care to avoid an error from what it might deem a circular reference?


Solution

  • This seems to be a Decorator pattern. Castle recognizes decorators when registered in a right order. For instance when registered like:

    container.Register(Component.For<IGetData<Customer>>().ImplementedBy<CustomerCache>());
    container.Register(Component.For<IGetData<Customer>>().ImplementedBy<CustomerRepository>());
    

    Then resolving IGetData<Customer> will return CustomerCache which decorates CustomerRepository.