【问题标题】:Is there a way to pass a child container into the NserviceBus pipeline?有没有办法将子容器传递到 NserviceBus 管道中?
【发布时间】:2015-05-04 05:36:43
【问题描述】:

问题:
发送到调用IBus.SendLocal 的WCF 服务的请求创建配置为InstancePerLifetimeScope() 的对象的两个实例

背景:
我正在使用Autofac.Integration.WCF(通过为每个 WCF 请求提供一个新的子范围,使一切都解决“每个请求”)

IBus.SendLocal 调用消息修改器,它被注入与 wcf 服务相同的资源类型

但是,会创建两个不同的实例。一个被注入到服务中,另一个实例被注入到消息修改器中。

我假设,这是因为 NSB 创建了自己的基于根容器的子范围。

任何想法/指针如何解决这个问题(即每个 WCF 请求只创建一个实例)?

编辑:使用 NSB 4.3.2 和 Autofac 3.5.2

简化配置代码

  Autofac.IContainer container = ConfigureIoc();

  Configure
    .With(AllAssemblies.Matching("this.dll").And("that.dll"))
    .DefineEndpointName("endpoint name here")
    .AutofacBuilder(container)
    .MsmqSubscriptionStorage()
    .UnicastBus()
    .CreateBus()
    .Start();

  ServiceHost host = CreateHost();
  host.AddDependencyInjectionBehavior(typeof(ISomeContract), container);
  host.Open();

【问题讨论】:

标签: c# wcf autofac nservicebus


【解决方案1】:

当 NServiceBus 接收到消息时,将创建一个子容器。在您的场景中,NServiceBus 未收到呼叫/消息,但 WCF 未收到呼叫/消息。然后,您进行的所有调用都将使用初始化 NServiceBus 时创建的根容器。

通过 Autofac 注册

builder.RegisterType<MyMutator>().AsImplementedInterfaces().AsSelf().InstancePerLifetimeScope();

通过 NServiceBus 注册

busConfiguration.RegisterComponents(x => x.ConfigureComponent<MyMutator>(DependencyLifecycle.InstancePerUnitOfWork));

当前 (v5) 无法在调用 Bus.SendLocal 时创建子容器,而不是在 NService 端点上接收消息的上下文中。

一种解决方案是将 WCF 调用转换为 one 消息并进行本地发送。然后,此消息将被处理为 NServiceBus 消息处理程序,该处理程序可以发送/发布多条消息并具有您需要的 mutator 行为(每个工作单元单个实例)。

我使用 WCF 和 NServiceBus 构建了一个示例项目,演示了工作单元生命周期范围行为:

https://github.com/ramonsmits/wcfnsbtest

【讨论】:

  • 感谢您的回复@Ramon。我仍然需要解决这个问题并扩展 NServiceBus.Autofac 以支持注入 ILifetimeScope 的工厂。
【解决方案2】:

修改 NServiceBus.Autofac object builder 以通过工厂启用子作用域解析。

ILifetimeScope 工厂返回一个 AutofacInstanceContext.Current.OperationLifetime,它是 WCF 使用的子容器。

https://github.com/Particular/NServiceBus.Autofac/pull/2

【讨论】:

    猜你喜欢
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多