56 lines
2.3 KiB
C#
56 lines
2.3 KiB
C#
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 RegisterInternals(this IServiceCollection services)
|
|
{
|
|
services.AddSingleton<ITypeRegistry, QueueTypeRegistry>();
|
|
services.AddTransient<ITaskRepository, TaskRepositoryInMemory>();
|
|
return services;
|
|
}
|
|
|
|
public static IServiceCollection RegisterQueues(this IServiceCollection services)
|
|
{
|
|
using var sp = services.BuildServiceProvider();
|
|
// find all types in the assembly that implement IQueueHandler<T>
|
|
var queueTypes = Assembly.GetExecutingAssembly().GetTypes()
|
|
.Where(t => t.IsClass && !t.IsAbstract && t.GetInterfaces()
|
|
.Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IQueueHandler<>)));
|
|
var hostedServiceRegistrator = new HostedServiceRegistrator();
|
|
|
|
// register each query type with its corresponding interface
|
|
foreach (var queueType in queueTypes)
|
|
{
|
|
// get the T from IQueueHandler<T>
|
|
var type = queueType.GetInterfaces()
|
|
.Single(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IQueueHandler<>));
|
|
|
|
// register the query type as a scoped service with its corresponding interface
|
|
services.AddScoped(queueType);
|
|
|
|
var typeRegistry = sp.GetRequiredService<ITypeRegistry>();
|
|
typeRegistry.RegisterTaskType(type.GenericTypeArguments.First().Name, type);
|
|
|
|
services.AddScoped(typeof(IQueueHandler<>)
|
|
.MakeGenericType(type.GenericTypeArguments), queueType);
|
|
|
|
//todo: bug here
|
|
var hostedServiceType = typeof(QueueService<>).MakeGenericType(type.GenericTypeArguments);
|
|
hostedServiceRegistrator.RegisterHostedService(services, hostedServiceType);
|
|
|
|
// services.AddSingleton(typeof(IQueueService<>)
|
|
// .MakeGenericType(type.GenericTypeArguments), );
|
|
}
|
|
return services;
|
|
|
|
}
|
|
|
|
|
|
} |