NServiceBus icon indicating copy to clipboard operation
NServiceBus copied to clipboard

Expose IServiceProvider on started endpoints

Open timbussmann opened this issue 2 years ago • 0 comments

Describe the suggested improvement

Is your improvement related to a problem? Please describe.

When using NServiceBus with the "default" DI container mode, which makes NServiceBus use an internally managed DI container, it can be difficult to access the actual DI container to resolve instances from the container. While the IServiceCollection API is accessible via the EndpointConfiguration API, the IServiceProvider is only accessible via workarounds.

This can be a challenge in the following two scenarios:

Describe the suggested solution

The IServiceProvider API might be exposed via the IRunningEndpointInstance or IMessageSession interfaces to be accessible once the endpoint has started.

Describe alternatives you've considered

The main alternatives are:

  • Using the more noisy externally managed DI container APIs which will leave the user with creating the IServiceProvider
  • Writing a custom Feature and FeatureStartupTask. The FetureStartupTask supports dependency injection on its constructor and it can be used to inject the IServiceProvider to be stored e.g. in a static field.
  • Writing a custom behavior in the pipeline that can access the IBehaviorContext.Builder property. This is more dangerous and error-prone as this will be a scoped IServiceProvider, scoped to the incoming message pipeline and not suitable to be stored and used outside the pipeline. This approach is not recommended.

Additional Context

No response

timbussmann avatar Oct 18 '23 09:10 timbussmann