NServiceBus
NServiceBus copied to clipboard
Expose IServiceProvider on started endpoints
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:
- NServiceBus or an NServiceBus downstream API exposes instances via the DI container. E.g. this is the case with the TransactionalSession or with some lower-level APIs like the
IMessageDispatcher. - Users may register their own types via the
EndpointConfiguration'sIServiceCollectionbecause there is no need to use the externally managed DI container APIs but they still want to resolve the registered types from the internally managed container.
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
FeatureandFeatureStartupTask. TheFetureStartupTasksupports dependency injection on its constructor and it can be used to inject theIServiceProviderto be stored e.g. in a static field. - Writing a custom behavior in the pipeline that can access the
IBehaviorContext.Builderproperty. This is more dangerous and error-prone as this will be a scopedIServiceProvider, 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