How to use the build-in IoC container from .NET Core

netcore

(Calvin) #1

The sample here is about using AutoFac and there are docs to use other ioc containers. However my projects are all using the built-in container from .Net Core. How do I integrate that with NServiceBus?

I think I have figured out everything else in using NSB in .NET Core and this is the last piece. I hope I will hear good news here. :slight_smile:


(Andreas Öhlund) #2

NServiceBus can’t currently be used with the built-in Asp.net core IoC container since it doesn’t support property injection which is required by NServiceBus.

More details here:

Depending on how many dependencies you have in your handlers one option could be to register them both in the asp.net core container and also the internal NServiceBus container?

https://docs.particular.net/nservicebus/dependency-injection


(Indu Alagarsamy) #3

HI Calvin,

I am curious as to what option you went with. What I ended up doing in a similar situation where I had to access the DBContext (which was registered in the asp.net core container) from the NServiceBus message handler was, I followed the sample you mentioned to essentially use a common container for both ASP Net core and NServiceBus using Autofac.
Other containers can also be used in a similar fashion.

Sample: https://docs.particular.net/samples/dependency-injection/aspnetcore/

Thanks,
Indu Alagarsamy
Particular Software


(Calvin) #4

Hi Indu,

I didn’t use Autofac or any other 3rd party IoC container. The built-in container has been working well for us and we don’t feel to introduce Autofac just for NserviceBus.

What I ended up doing was adding a public static property for IServiceProvider so that my event handler to resolve the needed interface manually (service locator). Not ideal but it’s an acceptable solution so far.

Thanks,
Calvin


(Indu Alagarsamy) #5

Hi Calvin,

Thanks for getting back. Makes sense. We’ll keep you posted if we get around the property injection and end up facilitating using the built in container for core.

Cheers,
Indu Alagarsamy
Particular Software