inversion-of-controlcastle-windsorioc-containeropen-genericscastle-windsor-3

How to automatically register open generic interface with Castle Windsor?


I need to automatically register my open generic interface to its implementation classes My interface is something like that IIntegrationEventHandler

public interface IIntegrationEventHandler<in TIntegrationEvent> 
    where TIntegrationEvent : BaseIntegrationEvent
{
    Task HandleAsync(TIntegrationEvent @event);
}

My handlers will be something like that

    public class EmployeeEventsHandler : IIntegrationEventHandler<EmployeeUserCreated>
{
    public async Task HandleAsync(EmployeeUserCreated @event)
    {
        throw new NotImplementedException();
    }        
}

Is there any general way in Castle Windsor to do such registration without manually do it with every handler, i searched a lot but nothing note that i don't have a base handler class, only the generic interface and the implementation classes


Solution

  • Registration by conventions should work here:

    var container = new WindsorContainer();
    
    container.Register(
        Classes.FromAssemblyNamed("YourHandlersAssemblyName")
        .BasedOn(typeof(IIntegrationEventHandler<>))
        .WithServiceFirstInterface());
    
    var handler = container.Resolve<IIntegrationEventHandler<EmployeeUserCreated>>();