Day 48 of #100DaysOfCode: Dependency Injection in ASP.NET MVC5 using Ninject
Tags: csharp, 100daysofcode, webdev, mvc
Published: 2020-11-18 12:09:15


##Introduction
The controller is tied to concrete implementation of service because the constructor of the HomeController has to create the instance of service.  

```c#
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.
1. It'll be easier to test the controller when we want to mock the service.
2. 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](http://www.ninject.org/)* 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

```c#
public interface IMessageService
{
    string GetWelcomeMessage();
}
```
### 4. Create a service implemented that interface
```c#
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()*
```c#
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.
 
```c#
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](https://medium.com/a-layman)
* [Facebook page](https://www.facebook.com/imalayman)
* [My web resume](https://jenhsuan.github.io/ALayman/cover.html)
* [Twitter bot](https://twitter.com/ALayman84368087)
* [Side project - Daily Learning](https://daily-learning.herokuapp.com/)

## References
* [How to use Ninject with ASP.NET Web API?](https://stackoverflow.com/questions/14016727/how-to-use-ninject-with-asp-net-web-api)
* [c# - Ninject to Web API:从NuGet安装后开始](https://www.coder.work/article/2889975)
* [ASP.NET MVC使用Ninject](https://www.itread01.com/content/1544259488.html)
* [Refactoring to Dependency Injection Principle](https://techiethoughtss.wordpress.com/2016/11/16/refactoring-to-dependency-injection-principle/)
* [Avoiding dependency carrying](https://stackoverflow.com/questions/2953266/avoiding-dependency-carrying)
* [Inversion of Control Containers and the Dependency Injection pattern
](https://martinfowler.com/articles/injection.html)
* [Dependency Injection in ASP.NET MVC4 and webapi using Ninject](https://www.codeproject.com/Articles/412383/Dependency-Injection-in-ASP-NET-MVC-and-webapi-usi)