Skip to content

Instantly share code, notes, and snippets.

@rmacfie
Last active July 12, 2022 12:42
  • Star 18 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save rmacfie/85b604a2faced2519454 to your computer and use it in GitHub Desktop.
Register MediatR handlers in Asp.Net 5 / vNext / Core
namespace Microsoft.AspNet.Builder
{
public static class MediatRExtensions
{
public static IServiceCollection AddMediatR(this IServiceCollection services, params Assembly[] handlerAssemblies)
{
services.AddTransient<IMediator>(x => new Mediator(x.GetService<SingleInstanceFactory>(), x.GetService<MultiInstanceFactory>()));
services.AddTransient<SingleInstanceFactory>(x => t => x.GetRequiredService(t));
services.AddTransient<MultiInstanceFactory>(x => t => x.GetServices(t));
foreach (var assembly in handlerAssemblies)
{
foreach (var type in assembly.ExportedTypes.Select(t => t.GetTypeInfo()).Where(t => t.IsClass && !t.IsAbstract))
{
var interfaces = type.ImplementedInterfaces.Select(i => i.GetTypeInfo()).ToArray();
foreach (var handlerType in interfaces.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IAsyncRequestHandler<,>)))
{
services.AddTransient(handlerType.AsType(), type.AsType());
}
foreach (var handlerType in interfaces.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(INotificationHandler<>)))
{
services.AddTransient(handlerType.AsType(), type.AsType());
}
foreach (var handlerType in interfaces.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IRequestHandler<,>)))
{
services.AddTransient(handlerType.AsType(), type.AsType());
}
}
}
return services;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment