Search code examples
nservicebus

Shared service provider NServiceBus and ASPNET Core


I'm creating a way to publish integration events via NServiceBus that are published from within an operation executed in a handler. The path I've chosen is bridge the IIntegrationEventProvider with IEventCollectionPublisher to get the published events from domain layer.

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;
}

Since NServiceBus has its own service provider (IBuilder) I need to resolve the class doing the application operation from the IServiceProvider that is made available to pipeline in ServiceScopedBehavior. Doing this I can get the bridge instance that contains the events published from domain layer and publish them as integration events using NServiceBus.

I published a Gist with (hopefully) the code pieces needed to grasp what I'm trying to achieve.

The question is: can I instruct NServiceBus to just delegate calls to the application service provider instead of building it and copy all instructions in endpoint.UserContainer<ServiceBuilder>()? Below is an example

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);
    }
}

This way I could inject to correct scoped application class in the handler constructor instead of resolving it from the scope provided by IServiceProvider that is made available from context.Extensions.Get<IServiceScope>().ServiceProvider.

Thanks for help

Regards


Solution

  • I think 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 that adds UseNServiceBus API.