Using an existing DI container

Hi, I have a Windows service (.Net FW 4.7.2) in which I’m using Nservicebus 7.2.0 and I have setup MS extensions DI.
I’d like to use the existing DI container, where I have a Singleton service configured. I want this service to be injected in one of my Handlers (so my Handler will call one of its methods and pass the new incoming message).
I was able to configure DI on my endpoint using a new container, so my Handler was injected with a new instance of my service:

var containerSettings = endpointConfiguration.UseContainer(new DefaultServiceProviderFactory());
containerSettings.ServiceCollection.AddSingleton();

Alternatively - is there another way to pass the incoming message object from my Handler to my service (which is Injected as Singleton, NOT static).
Thanks,
MK

Hi @manik,

Your scenario sounds like standard Dependency Injection behavior using NServiceBus.Extensions.DependencyInjection. Does the sample from docs resolve your issue? - NServiceBus.Extensions.DependencyInjection Usage • NServiceBus.Extensions.DependencyInjection Samples • Particular Docs

If you rather want to call your service outside the message handler you could try to use one of the Message Handling Pipeline ways - Message Handling Pipeline • NServiceBus • Particular Docs.

Check out also this article - Infrastructure soup • Particular Software

Hope this help.

Thanks.

The standard integration of DI sample did not refer to using an existing container. However I was able to resolve this by configuring DI for the endpoint and injecting an instance of a service provided by app’s main container to the new NSB container. Then
I was able to consume this service in my handler and use it there, leaving the handler slim.

Hi,
i have the same problem, i’m already doing the container setup in my code;

var builder = new ServiceCollection();
builder.AddScoped etc…
var container = builder.BuildServiceProvider();

i would like to share the container cfg/instance with nsb, how should i do that ?
EDIT :
I guess i found it

Thanks

1 Like