DependencyInjection.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using Application.Abstractions.Messaging;
  2. using Application.Messaging;
  3. using Microsoft.Extensions.DependencyInjection;
  4. namespace Application;
  5. public static class DependencyInjection
  6. {
  7. private static readonly Type[] HandlerInterfaces =
  8. [
  9. typeof(ICommandHandler<>),
  10. typeof(ICommandHandler<,>),
  11. typeof(IQueryHandler<,>)
  12. ];
  13. public static IServiceCollection AddApplication(this IServiceCollection services)
  14. {
  15. var assembly = typeof(DependencyInjection).Assembly;
  16. foreach (var implementationType in assembly.GetTypes())
  17. {
  18. if (implementationType.IsAbstract || implementationType.IsInterface || implementationType.IsGenericTypeDefinition)
  19. {
  20. continue;
  21. }
  22. foreach (var serviceType in implementationType.GetInterfaces())
  23. {
  24. if (serviceType.IsGenericType && HandlerInterfaces.Contains(serviceType.GetGenericTypeDefinition()))
  25. {
  26. services.AddScoped(serviceType, implementationType);
  27. }
  28. }
  29. }
  30. services.AddScoped<Sender>();
  31. services.AddScoped<ISender>(sp => sp.GetRequiredService<Sender>());
  32. services.AddScoped<IMediator>(sp => sp.GetRequiredService<Sender>());
  33. return services;
  34. }
  35. }