using System.Reflection; using System.Runtime.CompilerServices; using WmsLite.Api.Repositories; using WmsLite.Api.Repositories.Interfaces; namespace WmsLite.Api.Infrastructure; public static class ServiceCollectionExtensions { public static IServiceCollection AddWmsLiteServices(this IServiceCollection services) { services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>)); services.AddScoped(); services.RegisterByConvention( typeof(ServiceCollectionExtensions).Assembly, "WmsLite.Api.Repositories.Interfaces", "WmsLite.Api.Repositories"); services.RegisterByConvention( typeof(ServiceCollectionExtensions).Assembly, "WmsLite.Api.Services.Interfaces", "WmsLite.Api.Services"); return services; } private static IServiceCollection RegisterByConvention( this IServiceCollection services, Assembly assembly, string interfaceNamespace, string implementationNamespace) { var implementationTypes = assembly.GetTypes() .Where(type => type is { IsClass: true, IsAbstract: false } && type.Namespace == implementationNamespace && !type.IsNested && type.GetCustomAttribute() is null) .ToDictionary(type => type.Name, StringComparer.Ordinal); var interfaceTypes = assembly.GetTypes() .Where(type => type is { IsInterface: true, IsGenericTypeDefinition: false } && type.Namespace == interfaceNamespace && type.GetCustomAttribute() is null); foreach (var interfaceType in interfaceTypes) { var implementationName = interfaceType.Name.StartsWith('I') ? interfaceType.Name[1..] : interfaceType.Name; if (implementationTypes.TryGetValue(implementationName, out var implementationType) && interfaceType.IsAssignableFrom(implementationType)) { services.AddScoped(interfaceType, implementationType); } } return services; } }