NinjectModules

NinjectModules allow us to define bindings in assemblies without the need to resort to passing around an instance of the IKernel.

So let’s look at an example. We have an EXE project and another project which contains the common interfaces used in the application. Let’s assume we have an IAdministrationSettings interface in the “common” project. The main application has classes and/or properties which have service dependencies on IAdministrationSettings.

Now we create a third project which will contain the implementations of the interfaces used in our application. So it’s got a reference to the common interfaces project/DLL but has no knowledge of the EXE and likewise the EXE has no knowledge of the implementation project.

So we want to now bind our implementation to the interface and have it automatically injected into our EXE.

In the implementation project we add the usual NInject references (or use NuGet to do it) and create a file, mines called Module.cs but the name doesn’t matter. Then we place the following code into the file

public class Module : NinjectModule
{
   public override void Load()
   {
      Bind<IAdministrationSettings>().To<AdministrationSettings>().InSingletonScope();
   }
}

We’ve declared a NinjectModule (there could be more than one) which define the bindings of our interface(s) to implementation(s), but we now need Ninject in the EXE to load these modules and hence allow it to bind the correct implementation, so we use the following code in the EXE

IKernel kernel = new StandardKernel();
kernel.Load("*.dll");

The above used the wildcard to load any/all DLL’s which have NinjectModules, alternatively we could store the implementations in “known” locations or ofcourse put the actual path to the DLL into this method.

Now Ninject will automatically handle the bindings.