Skip to content

Instantly share code, notes, and snippets.

@KingsleyOmon-Edo
Forked from rmacfie/MediatRExtensions.cs
Created February 26, 2020 00:46
Show Gist options
  • Save KingsleyOmon-Edo/4d836e670bd1c372dc8b6f2e57bc6b53 to your computer and use it in GitHub Desktop.
Save KingsleyOmon-Edo/4d836e670bd1c372dc8b6f2e57bc6b53 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