Introduction
The controller is tied to concrete implementation of service because the constructor of the HomeController has to create the instance of service.
public HomeController()
{
_messageService = new MessageService();
}
public ActionResult About()
{
ViewBag.Message = _messageService.GetWelcomeMessage();
return View();
}
There are a few advantages If we can decouple the controller with others.
- It'll be easier to test the controller when we want to mock the service.
- It'll ensure the single responsibility principle. It means that we only have to concern that how do we retrieving the data and not the concrete implementation.
Ninject is a Dependency Injection framework to break applications into loosely-coupled, highly-cohesive components, and then glue them back together.
Steps
1. Create a ASP.NET MVC project
2. Install packages
Install-Package Ninject -Version 3.3.4
Install-Package Ninject.MVC5 -Version 3.3.0
Install-Package Ninject.Web.Common.WebHost -Version 3.3.2
3. Create an interface
public interface IMessageService
{
string GetWelcomeMessage();
}
4. Create a service implemented that interface
public class MessageService : IMessageService
{
public string GetWelcomeMessage()
{
return "Welcome to Ninject MVC5 Example";
}
}
5. Edit App_Start/NinjectWebCommon.cs
It will generate NinjectWebCommon.cs after installing packages automatically. Add the following code in CreateKernel()
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
kernel.Bind<IMessageService>().To<MessageService>();
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
6. Edit Controllers/HomeController.cs
Now We can use dependency injection instead of creating instances in the controller.
public class HomeController : Controller
{
private readonly IMessageService _messageService;
public HomeController(IMessageService messageService)
{
_messageService = messageService;
}
...
public ActionResult About()
{
ViewBag.Message = _messageService.GetWelcomeMessage();
return View();
}
...
}
That's it!
Articles
There are some of my articles and released projects. Feel free to check if you like!
- My blog-posts for software developing
- Facebook page
- My web resume
- Twitter bot
- Side project - Daily Learning
References
- How to use Ninject with ASP.NET Web API?
- c# - Ninject to Web API:从NuGet安装后开始
- ASP.NET MVC使用Ninject
- Refactoring to Dependency Injection Principle
- Avoiding dependency carrying
- Inversion of Control Containers and the Dependency Injection pattern
- Dependency Injection in ASP.NET MVC4 and webapi using Ninject
Top comments (0)