0

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

joacar
  • 891
  • 11
  • 28

1 Answers1

1

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.

Szymon Pobiega
  • 3,358
  • 17
  • 18
  • That sample is what I was looking for. Looking forward to the release date, hopefully next week. Thanks – joacar Oct 17 '19 at 14:45
  • 1
    We've just released a helper package to simplify things further https://discuss.particular.net/t/nservicebus-extensions-hosting-1-0-0-major-release-available/1481 – Szymon Pobiega Nov 14 '19 at 08:24