Search code examples
c#rabbitmqsimple-injectoreasynetq

How to use Simple Injector with EasyNetQ?


Trying to configure the Simple Injector DI library with EasyNetQ. What is the correct way to achieve this?

There is NuGet package available 'EasyNetQ.DI.SimpleInjector' which is included in the project. Added code like InjectionExtensions.RegisterAsEasyNetQContainerFactory(container);. But, when trying to create the Bus like Bus = RabbitHutch.CreateBus(<ConnectionString>). It is throwing an error like

The container can't be changed after the first call to GetInstance, GetAllInstances and Verify

If I register Bus object with Simple Injector like

container.Register<IBus>(() => RabbitHutch.CreateBus(
    "username=guest;password=guest;virtualHost=chidemo;host=localhost"),
    Lifestyle.Singleton);

And then inject it using constructor then it works fine. But then it looks like not a correct use of 'EasyNetQ.DI.SimpleInjector' package.

Can anyone suggest correct approach or share working code snippet?

@dotnetjunkie @gpauls: if you can provide an expert opinion then that will be great!


Solution

  • I've not written the package, but if this:

    container.Register<IBus>(() => RabbitHutch.CreateBus(
        "username=guest;password=guest;virtualHost=chidemo;host=localhost"),
        Lifestyle.Singleton);
    

    Works for you that seems like a perfectly legal solution to me.

    Here's a unit test, but it only seems to mock the IBus, not instantiate it: https://github.com/EasyNetQ/EasyNetQ/blob/master/Source/EasyNetQ.DI.Tests/SimpleInjectorAdapterTests.cs

    Unfortunately EasyNetQ wasn't built with separate configure/build steps in mind for DI construction, so the container needs to support runtime registration of components.

    If it doesn't work for you somehow, please file an issue here: https://github.com/EasyNetQ/EasyNetQ/issues

    And maybe mention 'gpauls', he contributed SimpleInjector package, he might have a working sample solution.