Configuring NSB in .Net8 using generic host model and web hosting model

Hi @tmasternak, This is not a duplicate.

I am currently working on an application that utilizes dependency injection (DI) extensively, where various classes depend on each other to perform specific functionalities. These dependencies are registered in the DI container, and I resolve them through a service provider.

In particular, I am handling the creation of the EndpointConfiguration instance for NServiceBus (NSB), which can be delegated to a dedicated class. This class, in turn, might have its own dependencies. According to the NSB documentation, to register all necessary dependencies for NSB, we need to invoke Builder.UseNServiceBus, passing an EndpointConfiguration instance.

Given this scenario, I need to resolve the EndpointConfiguration instance, which requires building the IServiceCollection. When builder.Build() is called, .NET Core creates a service provider shared by both the framework and the NSB pipeline.

var builder = WebApplication.CreateBuilder(options);
builder.Services.AddTransient<IMyService, MyService>();
builder.Services.AddTransient<IMyDependency, MyDependency>();
builder.Services.AddTransient<IEndpointConfigurationProvider, EndpointConfigurationProvider>();

var serviceProvider = builder.Services.BuildServiceProvider(); // First Service Provider

var endpointConfigurationProvider = serviceProvider.GetRequiredService<IEndpointConfigurationProvider>();
var endpointConfiguration = endpointConfigurationProvider.CreateEndpointConfiguration();

builder.UseNServiceBus(endpointConfiguration);

var app = builder.Build(); // Second Service Provider
app.Run();

My question is: Is it possible to create the service provider only once and use the same instance to resolve the EndpointConfiguration and register all NSB dependencies? This would streamline the process and ensure consistency across the application.

I would appreciate your insights on the best approach to achieve this.

Thank you for your time and expertise.