Files
AIPS/dotnet/AipsCore/Infrastructure/DI/HandlerRegistrationExtensions.cs
2026-02-05 20:53:24 +01:00

42 lines
1.2 KiB
C#

using System.Reflection;
using AipsCore.Application.Abstract.Command;
using AipsCore.Application.Abstract.Query;
using Microsoft.Extensions.DependencyInjection;
namespace AipsCore.Infrastructure.DI;
public static class HandlerRegistrationExtensions
{
public static IServiceCollection AddHandlersFromAssembly(this IServiceCollection services, Assembly assembly)
{
var handlerInterfaces = new[]
{
typeof(ICommandHandler<>),
typeof(ICommandHandler<,>),
typeof(IQueryHandler<,>)
};
var types = assembly.GetTypes()
.Where(t => t is { IsAbstract: false, IsInterface: false });
foreach (var type in types)
{
var interfaces = type.GetInterfaces();
foreach (var @interface in interfaces)
{
if (!@interface.IsGenericType)
continue;
var genericDef = @interface.GetGenericTypeDefinition();
if (!handlerInterfaces.Contains(genericDef))
continue;
services.AddScoped(@interface, type);
}
}
return services;
}
}