Reputation: 25
In my startup of my WebApi project I've got the next code:
services.AddScoped<ICommandHandler<OpdrachtgeverToevoegenCommand>, OpdrachtgeverCommandHandler>();
services.AddScoped<ICommandHandler<OpdrachtgeverVerwijderenCommand>, OpdrachtgeverCommandHandler>();
services.AddScoped<ICommandHandler<OpdrachtgeverWijzigenCommand>, OpdrachtgeverCommandHandler>();
In my project I've got implementations of these interfaces.
Now I'm trying to find the correct implementation of this handler by using the command:
Here's the code that isn't completed yet:
public static ICommandHandler<ICommand> GetHandler(IServiceProvider serviceProvider, ICommand command)
{
if (serviceProvider == null) throw new ArgumentNullException(nameof(serviceProvider));
if (command == null) throw new ArgumentNullException(nameof(serviceProvider));
var handler = serviceProvider.GetRequiredService(command.GetType());
return serviceProvider.GetRequiredService(command.GetType()) as ICommandHandler<ICommand>;
}
I know that the command.GetType()
returns the correct command, but how do I find the ICommandHandler<command.GetType()>
implementation?
Upvotes: 1
Views: 342
Reputation: 21713
You could dynamically make the type that you are looking up using MakeGenericType
:
var handlerType = typeof(ICommandHandler<>).MakeGenericType(command.GetType());
return (ICommandHandler<ICommand>) serviceProvider.GetRequiredService(handlerType);
However, this will give you problems since I'm assuming that ICommandHandler<>
is not covariant. You will not be able to cast it to ICommandHandler<ICommand>
.
It's better to pass the type of command to the method as a generic argument.
public static ICommandHandler<TCommand> GetHandler<TCommand>(IServiceProvider serviceProvider, TCommand command)
{
return serviceProvider.GetRequiredService<ICommandHandler<TCommand>>();
}
Upvotes: 2