By default the NServiceBus generic host uses Spring for its IoC-needs. Changing this is as easy at it gets.

Note: If you’re hosting NServiceBus without the generic host, please follow this tutorial instead.

1. Select your desired IoC-container

NServiceBus comes with a built-in support for the following IoC-containers:

  • Spring
  • Autofac
  • Castle Windsor
  • Structuremap
  • Unity

You can pick your favorite. This tutorial will use the Structuremap.

2. Include the IoC-container in your project

Supported IoC-containers can be located from the NServiceBus/binaries/containers –folder. In Visual Studio, open up an NServiceBus application for which you want to change the IoC-container. Add a reference to the following files:

  • NServiceBus.ObjectBuilder.StructureMap.dll
  • StructureMap.dll

Note: Change the dlls if you selected an another IoC-container.

3. Modify the initialization

Now open the generic host initialization method. By default, it may look like something like this:

<span style="color: #606060" id="lnum1">   1:</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">class</span> ServerInit : IWantCustomInitialization, IWantCustomLogging

<span style="color: #606060" id="lnum2">   2:</span> {

<span style="color: #606060" id="lnum3">   3:</span>     <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Init()

<span style="color: #606060" id="lnum4">   4:</span>     {

<span style="color: #606060" id="lnum5">   5:</span>         NServiceBus.SetLoggingLibrary.Log4Net(log4net.Config.XmlConfigurator.Configure);

<span style="color: #606060" id="lnum6">   6:</span>     }

Modify this method by adding a call to NServiceBus.Configure.With().StructureMapBuilder() –method. This changes the IoC-container.

<span style="color: #606060" id="lnum1">   1:</span> <span style="color: #0000ff">public</span> <span style="color: #0000ff">void</span> Init()

<span style="color: #606060" id="lnum2">   2:</span> {

<span style="color: #606060" id="lnum3">   3:</span>     NServiceBus.Configure.With().StructureMapBuilder();

<span style="color: #606060" id="lnum4">   4:</span>     NServiceBus.SetLoggingLibrary.Log4Net(log4net.Config.XmlConfigurator.Configure);

<span style="color: #606060" id="lnum5">   5:</span> }

Simple, wasn’t it? The new method comes from the NServiceBus.ObjectBuilder.StructureMap.dll. If your application has already initialized an StructureMap container, you can pass it to the NServiceBus as a method parameter.