我收到错误Autofac.Core.DependencyResolutionException

时间:2019-06-21 05:36:45

标签: c# asp.net-mvc asp.net-web-api microservices cqrs

Autofac.Core.DependencyResolutionException   HResult = 0x80131500   Message =在激活Property.Service.API.Application.Commands.AddPropertyCommandHandler时引发了异常。   来源= Autofac   堆栈跟踪:    在Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable 1 parameters, Object& decoratorTarget) at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable 1个参数)处    在Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration注册,IEnumerable 1 parameters) at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable 1个参数,对象和实例)    在Property:Service.API.Infrastructure.AutofacModules.MediatorModule。<> c__DisplayClass0_0.b__5(类型t)在C:\ Property.Service \ Property.Service.Application \ Infrastructure \ AutofacModules \ MediatorModule.cs:第56行    在MediatR.ServiceFactoryExtensions.GetInstance [T](ServiceFactory工厂)    在MediatR.Internal.RequestHandlerBase.GetHandler [THandler](ServiceFactory factory)

内部异常1: DependencyResolutionException:在type.Property.Service.API.Application.Commands.AddPropertyCommandHandler'上使用'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'找到的所有构造函数都不能使用可用的服务和参数来调用: 无法解析构造函数'Void .ctor(Property.Service.Domain.AggregatesModel.PropertyAggregate.IPropertyRepository,MediatR.IMediator,Property.Service.API.Application.IntegrationEvents.IPropertyIntegrationEventService。 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());
        }

我已经这样注册的依赖性

    services.AddTransient<IPropertyIntegrationEventService, PropertyIntegrationEventService>();

1 个答案:

答案 0 :(得分:0)

无法将第3个构造函数参数IPropertyIntegrationEventService解析为PropertyIntegrationEventService的实现。

很清楚,介体和接口的定义位置:

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

不清楚在什么位置保留PropertyIntegrationEventService,以及是否在模块中注册了它所在的程序集。