Search code examples
c#castle-windsorcastle

Castle Windsor Register by Convention - how to register generic Repository based on Entity?


This should be a general problem, i've searched but couldn't found any solution yet, if it is a dupe, please point me appropriate link.

So, i have a generic repository to support several entites, for a moment i register it like bellow:

public class ExpensiveServiceInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        Register<EntityA>(container);
        Register<EntityB>(container);
        //etc etc 
        //when there is a new one should register it manually
    }

    void Register<T>(IWindsorContainer container) where T : Entity
    {
        container.Register(Component.For<IRepository<T>>()
            .ImplementedBy<Repository<T>>()
            .LifeStyle.Transient);
    }
}

Note:
Repository located on Repositories namespace
Entities located on Entities namespace, including the Entity baseclass of all entities

it is working fine, but i think it should be a better way, the more automatic way using registration by convention, so when i add a new entity on my project, windsor will automatically recognize it, and register repository for it. and one more question, how to ignore Entity (the base class) so it not registered on the container.

regards


Solution

  • You mean something like this?

    container.Register(Component.For(typeof(IRepository<>))
                .ImplementedBy(typeof(Repository<>))
                .LifeStyle.Transient);