public static IServiceCollection RegisterCommandHandlers(this IServiceCollection services, Assembly assembly, Type compareType)
{
services.AddScoped<ICommandHandler<CreateCommand>, CreateCommandHandler>(); // i have multiple registrations , this is a sample one jic
CommandDispatcher dispatcher = new();
foreach (var commandHandlerType in assembly.GetTypes()
.Where(type => type.GetInterfaces()
.Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICommandHandler<>))))
{
var commandType = commandHandlerType.GetInterfaces()
.Single(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICommandHandler<>))
.GetGenericArguments()[0];
Type genericType = typeof(ICommandHandler<>).MakeGenericType(commandType);
var commandHandler = services.BuildServiceProvider().GetRequiredService(genericType); //tried doing this beacuse idk what im doing
var handleAsyncMethod = commandHandlerType.GetMethod("HandleAsync");
if (handleAsyncMethod != null)
{
var handleDelegate = (Func<object, Task>)handleAsyncMethod.CreateDelegate(
typeof(Func<object, Task>).MakeGenericType(commandType, typeof(Task)),
commandHandler);
dispatcher.RegisterHandler(commandType, handleDelegate);
Console.Write("Registered a delegate");
}
else
{
Console.Write("here");
}
}
services.AddSingleton<ICommandDispatcher>(_ => dispatcher);
return services;
}