我正在尝试执行以下操作:
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<,>)).As(typeof(IPipelineBehavior<,>)).AsImplementedInterfaces();
builder.RegisterGeneric(typeof(TransactionBehaviour<,>)).As(typeof(IPipelineBehavior<,>)).AsImplementedInterfaces();
}
当我执行请求时:
await _mediator.Send(new ExampleQuery<ExampleClass1> { Id = id })
我收到以下错误:
System.InvalidOperationException:'找不到处理程序类型为 MediatR.IRequestHandler`2[ExampleQuery[ExampleClass1],ExampleClass1] 的请求。向容器注册您的处理程序。
我了解运行时无法找到具有提供的类的处理程序,因为它尚未正确注册。我想要实现的目标真的可能吗?我缺少 Autofac 配置中的任何内容吗?