调解员是单身人士吗



我在.Net Core项目中使用Mediator,我想知道Mediator中的处理程序是singleton的还是每个Send请求的新实例;我知道Mediator是Singleton,但对于它用于命令或查询的处理程序,我不太确定。

我倾向于认为他们也会是单身人士;但只是想再次确认。

事实上,所有这些东西的生命周期都有很好的记录https://github.com/jbogard/MediatR.Extensions.Microsoft.DependencyInjection/blob/master/README.md

仅供参考:IMediator是瞬态的(不是单例的(,IRequestHandler<gt;具体的实现是瞬态的等等,所以实际上它在任何地方都是瞬态的。

但请注意,将Scoped服务与Mediator处理程序一起使用,它不会像预期的那样工作,更像是singleton,除非手动创建范围。

对于处理程序,在遵循源代码之后,看起来它们都是作为Transient添加的。

https://github.com/jbogard/MediatR.Extensions.Microsoft.DependencyInjection/blob/1519a1048afa585f5c6aef6dbdad7e9459d5a7aa/src/MediatR.Extensions.Microsoft.DependencyInjection/Registration/ServiceRegistrar.cs#L57

services.AddTransient(@interface, type);

对于IMediator本身,默认情况下它看起来是生存期:

https://github.com/jbogard/MediatR.Extensions.Microsoft.DependencyInjection/blob/1519a1048afa585f5c6aef6dbdad7e9459d5a7aa/src/MediatR.Extensions.Microsoft.DependencyInjection/Registration/ServiceRegistrar.cs#L223

services.Add(new ServiceDescriptor(typeof(IMediator), serviceConfiguration.MediatorImplementationType, serviceConfiguration.Lifetime));

请注意,服务配置是一个配置对象,除非您以某种方式沿其默认路径更改它,否则它也将设置为瞬态:

public MediatRServiceConfiguration()
{
MediatorImplementationType = typeof(Mediator);
Lifetime = ServiceLifetime.Transient;
}

使用core,您可以手动注册处理程序并使用您想要的任何范围。例如:

services.AddScoped<IPipelineBehavior<MyCommand>, MyHandler>();

我们实际上包装了Mediator,这样我们就可以添加各种位和块,这样它就变成了这样的注册扩展(CommandContect/QueryContext保存了我们一直使用的各种东西,ExecutionResponse是一个标准响应,所以我们可以有标准的post处理程序来知道它们得到了什么(:

public static IServiceCollection AddCommandHandler<THandler, TCommand>(this IServiceCollection services)
where THandler : class, IPipelineBehavior<CommandContext<TCommand>, ExecutionResponse>
where TCommand : ICommand
{
services.AddScoped<IPipelineBehavior<CommandContext<TCommand>, ExecutionResponse>, THandler>();
return services;
}

它是这样使用的:

services.AddCommandHandler<MyHandler, MyCommand>();

我们有类似的查询(AddQueryHandler<…..(

希望能帮助

最新更新