我有一个带有Mediatr 3.0.1和structureMap.Microsoft.DependencyInjection 1.4.0的asp.net核心web api项目。
我想使用预处理和后处理行为。 IPipelineBehavior按预期工作,但是不要这样做:
public class PostProcessingBehavior<TRequest, TResponse> : IRequestPostProcessor<TRequest, TResponse>
{
public Task Process(TRequest request, TResponse response)
{
LogTo.Info("Post processing: All Done");
return Task.FromResult(0);
}
}
public class PreProcessingBehavior<TRequest>: IRequestPreProcessor<TRequest>
{
public Task Process(TRequest request)
{
// add validators here
LogTo.Info("Pipline preprocessing happens");
return Task.FromResult(0);
}
}
集装箱登记:
private IServiceProvider ConfigureIoC(IServiceCollection services)
{
var container = new Container();
container.Configure(cfg =>
{
cfg.Scan(scanner =>
{
scanner.AssemblyContainingType(typeof(Startup));
scanner.AssemblyContainingType(typeof(CustomerGetHandler));
scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<>)); // Handlers with no response
scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler<,>)); // Handlers with a response
scanner.ConnectImplementationsToTypesClosing(typeof(IAsyncRequestHandler<>)); // Async handlers with no response
scanner.ConnectImplementationsToTypesClosing(typeof(IAsyncRequestHandler<,>)); // Async Handlers with a response
scanner.ConnectImplementationsToTypesClosing(typeof(INotificationHandler<>));
scanner.ConnectImplementationsToTypesClosing(typeof(IAsyncNotificationHandler<>));
scanner.WithDefaultConventions();
});
cfg.For(typeof(IPipelineBehavior<,>)).Add(typeof(PreProcessingBehavior<>));
cfg.For(typeof(IPipelineBehavior<,>)).Add(typeof(LoggingBehavior<,>));
cfg.For(typeof(IPipelineBehavior<,>)).Add(typeof(PostProcessingBehavior<,>));
cfg.For<SingleInstanceFactory>().Use<SingleInstanceFactory>(ctx => t => ctx.GetInstance(t)).ContainerScoped();
cfg.For<MultiInstanceFactory>().Use<MultiInstanceFactory>(ctx => t => ctx.GetAllInstances(t)).ContainerScoped();
cfg.For<IMediator>().Use<Mediator>();
cfg.Populate(services);
});
return container.GetInstance<IServiceProvider>();
}
错误说:
ArgumentOutOfRangeException:指定的参数超出了有效值的范围。
参数名称:instance&#39; PostProcessingBehavior&#39; with ReturnType PostProcessingBehavior无法强制转换为IPipelineBehavior
这是来自这个例子: https://github.com/jbogard/MediatR/blob/master/samples/MediatR.Examples.StructureMap/Program.cs
答案 0 :(得分:1)
查看您链接到的示例似乎混淆了接口。
您已实施IRequestPostProcessor
&amp; IRequestPreProcessor
不是IPipelineBehavior
。
所以你应该注册你正在实现的接口:
cfg.For(typeof(IRequestPreProcessor<>)).Add(typeof(PreProcessingBehavior<>));
cfg.For(typeof(IRequestPostProcessor<,>)).Add(typeof(PostProcessingBehavior<,>));
从阅读documentation开始,您可能还需要注册以下内容
cfg.For(typeof(IPipelineBehavior<,>)).Add(typeof(RequestPreProcessorBehavior<,>));
cfg.For(typeof(IPipelineBehavior<,>)).Add(typeof(RequestPostProcessorBehavior<,>));