Skip to content

Configuring Nimbus With Ninject

Damian Maclennan edited this page Nov 10, 2017 · 4 revisions

We've gone through this blow by blow in the first section so if none of this makes sense go back and have a read there, let's just talk about the Ninject bits.

Getting Ninject

First thing you need to do is pull down Ninject. This is via NuGet of course.

Install-Package Nimbus.Ninject

Now we configure Nimbus and register it with the container

var connectionString = ConfigurationManager.AppSettings["BusConnectionString"];

var handlersAssembly = Assembly.GetExecutingAssembly();
var messagesAssembly = Assembly.GetExecutingAssembly();

// This is how you tell Nimbus where to find all your message types and handlers.
var handlerTypesProvider = new AssemblyScanningTypeProvider(handlersAssembly, messagesAssembly);

kernel.RegisterNimbus(handlerTypesProvider);
kernel.Bind<IBus>().ToMethod(
	componentContext => new BusBuilder()
		.Configure()
		.WithTransport(new InProcessTransportConfiguration()
		.WithNames("MyApp", Environment.MachineName)
		.WithTypesFrom(handlerTypesProvider)
		.WithNinjectDefaults(kernel)
		.Build())
	.InSingletonScope()
	.OnActivation(b => b.Start());
    kernel.Get<IBus>();

Breaking it down

Registering the handler types

kernel.RegisterNimbus(handlerTypesProvider);

There's an extension method that will register all of the various message handlers with the container. We call it with our handler type provider.

Ninject registration

kernel.Bind<IBus>().ToMethod(
	componentContext => new BusBuilder()
		.Configure()
		.WithConnectionString(connectionString)
		.WithNames("MyApp", Environment.MachineName)
		.WithTypesFrom(handlerTypesProvider)
		.WithNinjectDefaults(kernel)
		.Build())
	.InSingletonScope()
	.OnActivation(b => b.Start());

This is the configuration call we've already seen with one difference. We've already registered our handlers with Ninject but we need to tell the kernel how to build the configure the bus. You can dig into the source if you want to see how it works, but the .WithNinjectDefaults call is what you'll need.

Registering IBus

If you've used Ninject before you'll know you want to register the bus as an IBus so you can use it as a dependency in the rest of your code. We've configured it as InSingletonScope because we only want one instance of the bus in our app.

Starting the bus

Once the Bus is registered we want to start it. To do that we call kernel.Get<IBus>() which will instantiate Nimbus and call the "Start" method as per OnActivation.