Monday, April 4, 2011

Another IoC container-Ninject

In the previous articles(Unity(1), Unity(2),Unity(3),Unity(4)), I wrote some notes on Unity Container. Recently I used another IoC container -Ninject, which seems a bit lighterr and also easy to use. So I am going to write a bit notes on Ninject.

Here is the Site for Ninject. And .Codeplex has great reference on this as well.

Reference the assembly Ninject.Core.

using Ninject.Core;

We have an interface:

public interface IMyService
{
void Dowork();
}

We have a Service class:

public class MyService:IMyService
{
public void Dowork()
{
//...Write some code;
}
}

Now we create a CustomModule class inherited from StandardModule

public class CustomModule: StandardModule
{
public override void Load()
{
Bind< IMyService>().To< MyService>();
}
}

Notice this CustomModule class do the type mapping.

Once you create modules, you load them into a container called the kernel.

Now in the application entry (if it is console, in Main function, if this is a Asp.Net application we should reference the Ninject.Framework.Web assembly, add a global.asax file, and let the Global class inherited from NinjectHttpApplication)

Sample code:

class Program
{
static void Main(string[] args)
{
CustomModule module=new CustomModule();
IKernel kernel=new StandardKernel(module);
}
}

For Asp.Net application,

public class Global:NinjectHttpApplication
{
protected override IKernel CreateKernel()
{
CustomModule module=new CustomModule();
IKernel kernel=new StandardKernel(module);
return kernel;
}
}

When we want to resove the type from the container, it is also very simple:

For example, I have MyClass

public class MyClass
{
[Inject] //use the Inject attribute
public IMyService IMyService {get;set;}

protected void Method()
{
this.IMyService.Dowork();
//The method is called after resolving MyService from container
}
}

We will see use Ninject is simple, I will write some sample code on this later.

Some other points in Ninject is Contextual Binding, it is in the CustomModule class add conditions when do binding, it is also easy to understand, I am not going into details.

No comments: