Dependency Injection is an implementation of the Inversion of Control pattern. There are two possible implementations for IoC:
I've already discussed about What is DI and How to Use it Click here to Read about DI . here, in this Post I am Going to Use DI using NInject Container.
There are lots of IoC containers available:
NInject- Ninject is a lightning-fast, ultra-lightweight dependency injector for .NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner. By using Ninject to support your software's architecture, your code will become easier to write, reuse, test, and modify.
and MessageService:
The advantages of using Dependency Injection pattern and Inversion of Control are the following:
- Service Locator
- Dependency Injection
There are lots of IoC containers available:
- Unity
- CastleWindsor
- StructureMap
- Spring.NET
- Ninject
- Autofac
NInject- Ninject is a lightning-fast, ultra-lightweight dependency injector for .NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner. By using Ninject to support your software's architecture, your code will become easier to write, reuse, test, and modify.
Let’s start
Create a new Mvc 4 Project.
Add NInject from Manage Nuget Package Reference.
Add NInject from Manage Nuget Package Reference.
For demonstrating dependency injection we need some sort of interfaces and their concrete implementations, so in that regard I will add a new interface named IMessageService and it’s
implementation MessageService in the Model folder to the project root.
Here is the interface IMessageService:
public interface IMessageService
{
string GetMessage();
}
public class MessageService :IMessageService
{
public string GetMessage()
{
return "Hello India Won the
Match.";
}
}
Add a new class in Model name NInjectDependencyResolver that implements IDependencyResolver Interface and Implements it's two
functions object
GetService(Type serviceType) and IEnumerable<object>
GetServices(Type serviceType) for
DI work, so It can be implement like this:
using Ninject;
using Ninject.Syntax;
public class NInjectDependencyResolver : IDependencyResolver
{
private readonly IResolutionRoot _resolutionRoot;
public NInjectDependencyResolver(IResolutionRoot kernel)
{
_resolutionRoot = kernel;
}
public object GetService(Type serviceType)
{
return _resolutionRoot.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _resolutionRoot.GetAll(serviceType);
}
public static void setUpDependencyInjection()
{
//Create
NInject DI Kernel
IKernel kernel = new StandardKernel();
//Register
Services with NInject DI Container
kernel.Bind<IMessageService>().To<MessageService>();
//Tell
ASP.Net MVC to use our NInject DI COntainer
DependencyResolver.SetResolver(new NInjectDependencyResolver(kernel));
}
}
ok, in the method above setUpDependencyInjection() I created a standard kernel which is implemented in the Ninject.dll and bind our service to it’s concrete implementation, say whenever the application encounters the IMessageService then it will automatically creates a new instance of MessageService damn simple isn’t it, don’t forget to call above method in Application_Start().
Now in the Application_Start(), hook DI related stuff. Call setUpDependencyInjection function in Application_Start() Function.
protected void Application_Start()
{
......
...
...
NInjectDependencyResolver.setUpDependencyInjection();
}
To test it, open up HomeController and change it like that:
public class HomeController : Controller
{
private readonly IMessageService _messageService;
public HomeController(IMessageService messageservice)
{
this._messageService = messageservice;
}
public ActionResult Index()
{
ViewBag.Message =
_messageService.GetMessage();
return View();
}
}
First, I add a private readonly field _messageService that holds our service instance on the fly. I also add a class constructor which takes single parameter of type IMessageService and then set it to our private field.
In Index() ActionResult method I called the GetMessage() and we are done, look I didn’t create a new instance of MessageService class anywhere it will automatically created by our DI container.
Index.cshtml
<h2>@ViewBag.Message</h2>
<h2>@ViewBag.Message</h2>
Now Run the Application and see the output :
you see the message above it comes from our MessageService class’s GetMessage() method which I called in HomeController.
- Reduces class coupling
- Increases code reusing
- Improves code maintainability
- Improves application testing
Hope you understand how DI works in ASP.NET MVC 4 with Ninject.
Download the Complete Project here Click me -
Read More about NInject on Codeplex Click me -
Download the Complete Project here Click me -
Read More about NInject on Codeplex Click me -
To Install NInject go to package manager console and type
ReplyDeleteInstall-Package Ninject -Version 3.2.2
And Hit Enter