***** NOTE: This post was created because other posts on the net are outdated and the ninject libraries have changed. *****
When using any type of IoC container one of your goals needs to be to remove as much friction and ceremony as possible. One way to do this with an IoC container is to use convention based binding based on assembly scanning.
When using Ninject you can setup the container to bind via assembly scanning by using the Ninject.Extensions.Conventions extension and a few lines of code. Lets get rolling and learn how to do this
Getting the software:
Get Ninject – Download your correct platform version here
Get the Convention Extension – Download the binary or source here
Creating the Code to do assembly scanning:
Setup your Using Statements
using Ninject;
using Ninject.Extensions.Conventions;
Setup The Service location
private void StupServiceLocation()
{
IKernel ninjectKernel = new Ninject.StandardKernel();
// The AssemblyScanner is in the Ninject.Extensions.Conventions library
var ninjectAssemblyScanner = new AssemblyScanner();
// Here I am setting up the scanning in the assembly which contains the given interface
ninjectAssemblyScanner.FromAssemblyContaining<IMessageboxService>();
// This is important, without the call to using default conventions Ninject will not know how to
// bind an IFoo to the Foo instance
ninjectAssemblyScanner.BindWithDefaultConventions();
// Tell the ninject kernel to do its job
ninjectKernel.Scan( ninjectAssemblyScanner );
// Reach into the container and grab the instance you are looking for.
var messageBoxService = ninjectKernel.Get<IMessageboxService>();
}
OR use Lambda syntax
private void StupServiceLocation()
{
IKernel ninjectKernel = new Ninject.StandardKernel();
// If you would rather use the lamba syntax you can use the following
ninjectKernel.Scan( kernel =>
{
kernel.FromAssemblyContaining<IMessageboxService>();
kernel.BindWithDefaultConventions();
});
// Reach into the container and grab the instance you are looking for.
var messageBoxService = ninjectKernel.Get<IMessageboxService>();
}
As you can see setting up Ninject to setup it’s bindings based on assembly scanning is very easy and requires pretty much NO code.
Till next time,
Posted
06-30-2011 6:17 AM
by
Derik Whittaker