-
-
Save KingsleyOmon-Edo/4d836e670bd1c372dc8b6f2e57bc6b53 to your computer and use it in GitHub Desktop.
Register MediatR handlers in Asp.Net 5 / vNext / Core
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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