I am getting Error Autofac.Core.DependencyResolutionException

0

Autofac.Core.DependencyResolutionException HResult=0x80131500 Message=An exception was thrown while activating Property.Service.API.Application.Commands.AddPropertyCommandHandler. Source=Autofac StackTrace: at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable1 parameters, Object& decoratorTarget) at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable1 parameters) at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable1 parameters) at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable1 parameters, Object& instance) at Property.Service.API.Infrastructure.AutofacModules.MediatorModule.<>c__DisplayClass0_0.b__5(Type t) in C:\ Property.Service\ Property.Service.Application\Infrastructure\AutofacModules\MediatorModule.cs:line 56 at MediatR.ServiceFactoryExtensions.GetInstance[T](ServiceFactory factory) at MediatR.Internal.RequestHandlerBase.GetHandler[THandler](ServiceFactory factory)

Inner Exception 1: DependencyResolutionException: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type.Property.Service.API.Application.Commands.AddPropertyCommandHandler' can be invoked with the available services and parameters: Cannot resolve parameter 'Property.Service.API.Application.IntegrationEvents.IPropertyIntegrationEventService propertyIntegrationEventService' of constructor 'Void .ctor(Property.Service.Domain.AggregatesModel.PropertyAggregate.IPropertyRepository, MediatR.IMediator, Property.Service.API.Application.IntegrationEvents.IPropertyIntegrationEventService, Microsoft.Extensions.Logging.ILogger`1[Property.Service.API.Application.Commands.AddPropertyCommandHandler])'.

AddPropertyCommandHandler

public class AddPropertyCommandHandler : IRequestHandler<AddPropertyCommand, bool>
{
    private readonly IPropertyRepository _propertyRepository;
    private readonly IMediator _mediator;
    private readonly IPropertyIntegrationEventService _propertyIntegrationEventService;
    private readonly ILogger<AddPropertyCommandHandler> _logger;

    public AddPropertyCommandHandler(
        IPropertyRepository propertyRepository,
        IMediator mediator,
        IPropertyIntegrationEventService propertyIntegrationEventService,
        ILogger<AddPropertyCommandHandler> logger)
    {
        _propertyRepository = propertyRepository ?? throw new ArgumentNullException(nameof(propertyRepository));
        _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        _propertyIntegrationEventService = propertyIntegrationEventService;
    }

    public async Task<bool> Handle(AddPropertyCommand message, CancellationToken cancellationToken)
    {
        var propertyStartedIntegrationEvent = new PropertyStartedIntegrationEvent(message.ModifiedUserId);
        await _propertyIntegrationEventService.AddAndSaveEventAsync(propertyStartedIntegrationEvent);

        var property = new DomainModels.Property(message.PropertyId,message.PropertyType,message.PropertyLayout,message.PropertyPrice,message.Location,message.PropertyOwnerShip,message.PropertyFor,message.PictureUrl);

        foreach (var item in message.PropertyItems)
        {
            property.AddOrderItem(
                item.PropertyId,
                item.PropertyType,
                item.PropertyLayout,
                item.PropertyPrice,
                item.Location,
                item.PropertyOwnerShip,
                item.PropertyFor,
                item.PictureUrl);
        }

        _logger.LogInformation("----- Adding Property - Property: {@Property}", property);

        _propertyRepository.Add(property);

        return await _propertyRepository.UnitOfWork.SaveEntitiesAsync();
    }
}

MediatorModule

   public class MediatorModule : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {

            builder.RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly)
                .AsImplementedInterfaces();

            builder.RegisterAssemblyTypes(typeof(AddPropertyCommand).GetTypeInfo().Assembly)
                .AsClosedTypesOf(typeof(IRequestHandler<,>));
builder
                .RegisterAssemblyTypes(typeof(AddPropertyCommandValidator).GetTypeInfo().Assembly)
                    .Where(t => t.IsClosedTypeOf(typeof(IValidator<>)))
                    .AsImplementedInterfaces();
 builder.Register<ServiceFactory>(context =>
                {
                    var componentContext = context.Resolve<IComponentContext>();
                    return t => { object o; return componentContext.TryResolve(t, out o) ? o : null; };
                });

IPropertyIntegrationEventService

public interface IPropertyIntegrationEventService
    {
        Task PublishEventsThroughEventBusAsync();
        Task AddAndSaveEventAsync(IntegrationEvent evt);
    }

PropertyIntegrationEventService

private readonly Func<DbConnection, IIntegrationeventlogservice> _integrationEventLogServiceFactory;
        private readonly IEventBus _eventBus;
        private readonly RealxContext _realxContext;
        private readonly IntegrationEventLogContext _eventLogContext;
        private readonly IIntegrationeventlogservice _eventLogService;
        private readonly ILogger<PropertyIntegrationEventService> _logger;

        public PropertyIntegrationEventService(IEventBus eventBus,
            RealxContext realxContext,
            IntegrationEventLogContext eventLogContext,
            Func<DbConnection, IIntegrationeventlogservice> integrationEventLogServiceFactory,
            ILogger<PropertyIntegrationEventService> logger)
        {
            _integrationEventLogServiceFactory = integrationEventLogServiceFactory ?? throw new ArgumentNullException(nameof(integrationEventLogServiceFactory));
            _realxContext = realxContext ?? throw new ArgumentNullException(nameof(realxContext));
            _eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus));
            _eventLogContext = eventLogContext ?? throw new ArgumentNullException(nameof(eventLogContext));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        public async Task PublishEventsThroughEventBusAsync()
        {
            var pendingLogEvents = await _eventLogService.RetrieveEventLogsPendingToPublishAsync();

            foreach (var logEvt in pendingLogEvents)
            {
                _logger.LogInformation(
                    "----- Publishing integration event: {IntegrationEventId} from {AppName} - ({@IntegrationEvent})",
                    logEvt.EventId,
                    "PropertyService",
                    logEvt.IntegrationEvent);

                try
                {
                    await _eventLogService.MarkEventAsInProgressAsync(logEvt.EventId);
                    _eventBus.Publish(logEvt.IntegrationEvent);
                    await _eventLogService.MarkEventAsPublishedAsync(logEvt.EventId);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "ERROR publishing integration event: {IntegrationEventId} from {AppName}", logEvt.EventId, "PropertyService");

                    await _eventLogService.MarkEventAsFailedAsync(logEvt.EventId);
                }
            }
        }

        public async Task AddAndSaveEventAsync(IntegrationEvent evt)
        {
            _logger.LogInformation("----- Enqueuing integration event {IntegrationEventId} to repository ({@IntegrationEvent})", evt.Id, evt);

            //await _eventLogService.SaveEventAsync(evt, _realxContext.GetCurrentTransaction.GetDbTransaction());
        }

Dependency I Have Register Like this

    services.AddTransient<IPropertyIntegrationEventService, PropertyIntegrationEventService>();
c#
asp.net-mvc
asp.net-web-api
microservices
cqrs
asked on Stack Overflow Jun 21, 2019 by JP217 • edited Jun 21, 2019 by JP217

1 Answer

1

It fails to resolve the 3rd constructor argument IPropertyIntegrationEventService to implementation of PropertyIntegrationEventService.

While it is clear where mediator and the interface is defined:

Property.Service.Application\Infrastructure\AutofacModules\MediatorModule
Property.Service.API.Application.IntegrationEvents.IPropertyIntegrationEventService 

It is not clear where you keep PropertyIntegrationEventService and if the assembly where it is locatad is registered in the module.

answered on Stack Overflow Jun 21, 2019 by Margus • edited Jun 21, 2019 by Margus

User contributions licensed under CC BY-SA 3.0