My application has two command classes FooCommand and BarCommand, where BarCommand is a subclass of FooCommand.
class FooCommand
class BarCommand : FooCommand
I then have classes to execute these commands.
class FooCommandHandler : ICommandHandler<FooCommand>
class BarCommandHandler : ICommandHandler<BarCommand>
These command handlers are registered with Autofac as ICommandHandler<> services.
builder.RegisterType<FooCommandHandler>.As<ICommandHandler<FooCommand>>();
builder.RegisterType<BarCommandHandler>.As<ICommandHandler<BarCommand>>();
Then when I need to execute a command, I resolve the registered handlers using Autofac's enumeration relationship type, which works fine.
var barCommandHandlers = container.Resolve<IEnumerable<ICommandHandler<FooCommand>>>()
// returns [ FooCommandHandler ]
So far, so good. But when I resolve registered handlers for BarCommand, Autofac matches both the BarCommandHandler and FooCommandHandler implementations because BarCommand derives from FooCommand.
var barCommandHandlers = container.Resolve<IEnumerable<ICommandHandler<BarCommand>>>()
// returns [ BarCommandHandler, FooCommandHandler ]
This behaviour isn't too unexpected, but it's not quite what I want.
Is there a way to resolve IEnumerable<ICommandHandler<BarCommand>> to only provide handlers that directly implement the ICommandHandler<BarCommand> interface, without also including those that implement ICommandHandler<Base>?