Tuesday, January 8, 2019

In this post we are going to install Ninject which is a lightweight IOC container. You can think of an IOC container as a magic toolbox that gives you the tools that you need when you need it. Hence its called dependency injection, meaning it injects the dependencies that you need. As with any IOC container there needs to be a mapping between the interfaces and the implementation. That's where Ninject comes in.

First let's install Ninject with Nuget. here are the steps:

1. Open the Nuget Management Console and type in the following command

Don't worry about the package call Ninject.Mvc3 it works perfectly with MVC 5.

2. Now we are going to set up Ninject by first creating an infrastructure folder. This folder will contain all of the plumbing stuff that we would need for our application. In the folder we are going to create an Ninject dependency resolver. Its just what the name implies the dependency will resolve the dependencies that we need, or you call it the mappings and configurations for the dependencies.
So create a folder call "Infrastructure" and add a new file call, "DependencyMappings" inside the folder.

It implements the IDependencyResolver interface from the System.Web.Mvc namespace. The IDependencyResolver interface gets your services and maps the dependencies to them.

It simply has two GetService(Type) and GetServices(Type) which is pretty much self explanatory.

So the code so far, for the DependencyMappings.cs file should look like the following:

The magic is in Ninject's Kernel object which has the job of resolving dependencies and instantiating the appropriate class instance. The client does not care about the implementation is instantiated it just request a certain type of object and gets back the implementation. For now we are going to leave the Bindings method not implemented because we still have not build out our business models.

The next thing we need to do is register our DependencyMappings class to Ninject. When we install Ninject a file was created to do just that called the NinjectWebCommon.cs file. The method to register the dependency resolver is the RegisterServices method