jeudi 13 octobre 2022

System.AggregateException: 'Some services are not able to be constructed only when running through visual studio

I'm registering some services for MediatR with reflection in my web api app with .NET6.

When I'm running the application from docker/command prompt the application running successfully. When I'm trying to run the application from visual studio with/without debugging I'm getting the next error:

InvalidOperationException: Unable to resolve service for type 'Verte.UnifiedCommerce.MessagingModel.WarehouseManagement.AsnCommands.AsnGenerationCommand' while attempting to activate 'Verte.UnifiedCommerce.DomainModel.Cqrs.Commands.Events.SagaInitiationCommand`1[Verte.UnifiedCommerce.MessagingModel.WarehouseManagement.AsnCommands.AsnGenerationCommand]'.

My code to register the services is:

var eventType = typeof(IApplicationEvent);

var assemblies = typeof(AsnGenerationSaga).Assembly.GetReferencedAssemblies()
    .Select(a => Assembly.Load(a))
    .ToArray();

var commands = assemblies.SelectMany(a => a.GetTypes())
    .Where(t => !t.Name.Contains("ClientNotificationCommand") && !t.IsInterface && !t.IsAbstract && t.GetInterfaces().Any(i => i.FullName == eventType.FullName) && (t.IsSubclassOf(typeof(Command)) || t.IsSubclassOf(typeof(ModificationCommand))))
    .ToArray();

var events = assemblies.SelectMany(a => a.GetTypes())
    .Where(t => !t.IsInterface && !t.IsAbstract && t.GetInterfaces().Any(i => i.FullName == eventType.FullName) && t.IsSubclassOf(typeof(SagaEvent)))
    .ToArray();

services.AddMediatR(typeof(ProductsReader).Assembly);

foreach (var type in commands)
{
    var sagaInitiationCommandType = typeof(SagaInitiationCommand<>).MakeGenericType(type);
    var irequestHandlerType = typeof(IRequestHandler<,>).MakeGenericType(sagaInitiationCommandType, typeof(Unit));
    var sagaEventInitiatorType = typeof(SagaEventInitiator<,>).MakeGenericType(sagaInitiationCommandType, type);

    if (sagaEventInitiatorType != null)
    {
        services.AddTransient(typeof(IRequest<Unit>), sagaInitiationCommandType);
        services.AddTransient(irequestHandlerType, sagaEventInitiatorType);
    }
}

foreach (var type in events)
{
    var sagaPublishCommandType = typeof(SagaPublishEvent<>).MakeGenericType(type);
    var irequestHandlerType = typeof(IRequestHandler<,>).MakeGenericType(sagaPublishCommandType, typeof(Unit));
    var sagaEventInitiatorType = typeof(SagaEventInitiator<,>).MakeGenericType(sagaPublishCommandType, type);

    if (sagaEventInitiatorType != null)
    {
        services.AddTransient(typeof(IRequest<Unit>), sagaPublishCommandType);
        services.AddTransient(irequestHandlerType, sagaEventInitiatorType);
    }
}




Aucun commentaire:

Enregistrer un commentaire