问题描述
我正在尝试使用NServiceBus Behavior
中的Scoped
依赖项.
I'm trying to use a Scoped
dependency from a NServiceBus Behavior
.
来自 NServiceBus行为文档:
由于Behavior
是Singleton,并且Behavior
的Invoke
方法不允许注入任何依赖项(例如,网络核心中间件的invoke
方法,因为在这种情况下,这是常规的接口实现),我不能在这里使用scoped
依赖项.
Since a Behavior
is a Singleton and the Invoke
method of the Behavior
doesn't allow to inject any dependency (such as the invoke
method of a net core middleware because in this case it's a regular interface implementation), I can't use a scoped
dependency from here.
我试图通过在构造函数中传递IServiceCollection来解决我的Invoke
方法中对每个传入/传出消息的依赖关系:
I've tried to resolve my dependencies in my Invoke
method for each incoming/outgoing message by passing IServiceCollection in the constructor:
private readonly IServiceCollection _services;
public MyIncomingMessageBehavior(IServiceCollection services)
{
_services = services;
}
public override async Task Invoke(IIncomingLogicalMessageContext context, Func<Task> next)
{
var myScopedDependency = _services.BuildServiceProvider().GetService<IMyScopedDependency>();
// always
}
总而言之,我的作用域依赖项包含当前上下文的数据,我想从我的Behavior
单例的Invoke
方法访问此数据吗?
In summary, my scoped dependency contains data for the current context and I'd like to access this data from the Invoke
method of my Behavior
singleton?
有什么办法吗?
推荐答案
您需要先创建作用域,然后再解决依赖项:
You need to create a scope before resolving your dependency:
private readonly IServiceScopeFactory _scopeFactory;
public MyIncomingMessageBehavior(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
public override async Task Invoke(IIncomingLogicalMessageContext context, Func<Task> next)
{
using(var scope = _scopeFactory.CreateScope())
{
var myScopedDependency = scope.ServiceProvider.GetService<IMyScopedDependency>();
}
}
此外,请注意,您的依赖项会与范围一起处置.
Also, pay attention that your dependency is disposed along with scope.
这篇关于NServiceBus Behavior中的范围依赖项使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!