共享服务提供者 NServiceBus 和 ASPNET Core

Shared service provider NServiceBus and ASPNET Core

我正在创建一种通过 NServiceBus 发布集成事件的方法,这些事件是从在处理程序中执行的操作中发布的。我选择的路径是将 IIntegrationEventProviderIEventCollectionPublisher 桥接,以从域层获取已发布的事件。

public sealed class Bridge : IIntegrationEventProvider /* Infrastructure */,
                             IEventCollectionPublisher /* Domain */
{
   private readonly List<object> _events = new List<object>();

   void IEventCollectionPublisher.Publish(object domainEvent) { _events.Add(domainEvent): }

   IReadOnlyCollection IIntegrationEventProvider.GetEvents() => _events;
}

由于 NServiceBus 有自己的服务提供者 (IBuilder),我需要解决 class 从 IServiceProvider 执行应用程序操作的问题,该操作可用于 [=16] 中的管道=].这样做我可以获得包含从域层发布的事件的桥实例,并使用 NServiceBus 将它们发布为集成事件。

我发布了一个 Gist,其中包含(希望)掌握我正在努力实现的目标所需的代码片段。

问题是:我可以指示 NServiceBus 仅将调用委托给应用程序服务提供者而不是构建它并复制 endpoint.UserContainer<ServiceBuilder>() 中的所有指令吗?下面是一个例子

internal sealed class Handler : IHandleMessages<Command>
{      
    public async Task Handle(Command message, IMessageHandlerContext context)
    {
        // Resolved from ASPNET DI
        var useCase = context.GetService<CommandUseCase>();
        // _useCase is resolved NSB DI since injected from constructor
        Debug.Assert(ReferenceEquals(useCase, _useCase), "");
        await useCase.Execute().ConfigureAwait(false);
    }
}

这样我就可以在处理程序构造函数中注入正确的作用域应用程序 class,而不是从 IServiceProvider 提供的作用域中解析它,该作用域可从 context.Extensions.Get<IServiceScope>().ServiceProvider.

感谢帮助

此致

我认为 ASP.NET Core integration sample could be useful. Starting from version 7.2 sharing of the DI infrastructure between ASP.NET and NServiceBus is much simpler. There is also a specialized NServiceBus.Extensions.Hosting adapter package 添加 UseNServiceBus API.