向接口注册 IRequest

问题描述

我正在尝试执行以下操作:

public interface IExampleDto { }

public class ExampleClass1 : IExampleDto { )
public class ExampleClass2 : IExampleDto { )

public class ExampleQuery<TProjection> : IRequest<TProjection>
    where TProjection : IExampleDto
{
    public Guid Id { get; set; }
}

public class ExampleQueryHandler<TProjection> : IRequestHandler<ExampleQuery<TProjection>,TProjection>
   where TProjection : IExampleDto
{
    public async Task<TProjection> Handle(ExampleQuery<TProjection> request,CancellationToken cancellationToken)
    {
        return await _context.Example.Where(e => e.Id == request.Id)
            .ProjectTo<TProjection>(_mapper.ConfigurationProvider).FirstOrDefaultAsync(cancellationToken);
    }
}

我的 Autofac 配置如下:

protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterassemblyTypes(typeof(IMediator).GetTypeInfo().Assembly)
            .InstancePerLifetimeScope()
            .AsImplementedInterfaces();
         
        // Register all the Command classes (they implement IRequestHandler) in assembly holding the Commands
        builder.RegisterassemblyTypes(typeof(UpdateElementTypeCommand).GetTypeInfo().Assembly)
            .AsClosedTypesOf(typeof(IRequestHandler<,>))
            .AsImplementedInterfaces()
            .InstancePerDependency();

        // Register the DomainEventHandler classes (they implement INotificationHandler<>) in assembly holding the Domain Events
        builder.RegisterassemblyTypes(typeof(ElementDomainEventHandler).GetTypeInfo().Assembly)
            .AsClosedTypesOf(typeof(INotificationHandler<>));

        // Register the Command's Validators (Validators based on FluentValidation library)
        builder
            .RegisterassemblyTypes(typeof(CreateNewCategoryCommandValidator).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; };
        });

        builder.RegisterGeneric(typeof(LoggingBehavior<,>)).As(typeof(IPipelineBehavior<,>)).AsImplementedInterfaces();
        builder.RegisterGeneric(typeof(ValidatorBehavior<,>)).AsImplementedInterfaces();
        builder.RegisterGeneric(typeof(TransactionBehavIoUr<,>)).AsImplementedInterfaces();
    }

当我执行如下请求时:

await _mediator.Send(new ExampleQuery<ExampleClass1> { Id = id })

我收到以下错误

system.invalidOperationException: '找不到 MediatR.IRequestHandler`2[ExampleQuery[ExampleClass1],ExampleClass1] 类型请求的处理程序。向容器注册您的处理程序。'

我知道运行时无法找到具有提供类的处理程序,因为它没有正确注册。 我正在努力实现的目标实际上可能吗? Autofac 配置中是否有任何我遗漏的内容

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)