using System.Reflection; using InServiceQue.Core.Models; using InServiceQue.Core.Repositories; using InServiceQue.InMemory; using InServiceQue.Services; using Microsoft.Extensions.DependencyInjection.Extensions; namespace InServiceQue.Sample; public static class DIExtensions { public static IServiceCollection RegisterQueues(this IServiceCollection services) { using var sp = services.BuildServiceProvider(); var queueHandlerType = typeof(IQueueHandler<>); // find all types in the assembly that implement IQueueHandler var queueTypes = Assembly.GetExecutingAssembly().GetTypes() .Where(t => t.IsClass && !t.IsAbstract && t.GetInterfaces() .Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == queueHandlerType)); var hostedServiceRegistrator = new HostedServiceRegistrator(); // register each query type with its corresponding interface foreach (var queueType in queueTypes) { // get the T from IQueueHandler var taskType = queueType.GetInterfaces() .Single(i => i.IsGenericType && i.GetGenericTypeDefinition() == queueHandlerType); // register the query type as a scoped service with its corresponding interface services.AddScoped(queueType); var typeRegistry = sp.GetRequiredService(); typeRegistry.RegisterTaskType(taskType.GenericTypeArguments.First().Name, taskType); services.AddScoped(queueType); var hostedServiceType = typeof(QueueService<>).MakeGenericType(taskType.GenericTypeArguments); hostedServiceRegistrator.RegisterHostedService(services, hostedServiceType); } return services; } }