Microsoft Dependency Injection and MVC6

In my previous blog post I’ve implemented a very simple application to illustrate dependency injection (DI) using Ninject. While Ninject is flexible and powerful, you might want to try different dependency injection libraries before you make your final decision on what to use. And this time I wanted to look into the latest dependency injection library which comes as a default option for MVC 6 and .NET Core – Microsoft Dependency Injection. And yes, the name is very easy to remember :)

Action!

I will be using the same code example as in my previous blog post, however the web application will be built using MVC 6 and .NET Core. If you want to go ahead and just check the source code instead of reading the whole blog post — you can download the source code here.

Let’s create solution and projects we will need. Open Visual Studio 2015 and let’s do following.

  1. Create a new web application for .NET 4.6.1.
    web application mvc6
  2. Choose .NET 5 template for the web application.
    .NET 5 templates
  3. Add two class libraries as packages (see screenshot #1). As you probably have noticed, .NET Core uses JSON and nuget packages for everything :) No more standard class library projects, they have to be packages.
  4. Copy the same HomeController, Views, ITestService and TestService code from the previous blog post – no changes here.
    solution structure
  5. And now instead of Ninject which was used the last time, let’s use Microsoft Dependency Injection to see how easy it’s to use it together with MVC 6 and .NET Core.
    • Open Startup.cs file, it should be in the root of your web application.
    • Locate ConfigureServices() method.
    • And simply add your code at the end of it. I’ve added a single line only.

services.AddSingleton<ITestService, TestService>();

That’s it! Compile your application and you should get the following result.

Bottom line

To sum up, Microsoft is trying hard to catch up with the latest development trends and offering built in (added by default) dependency injection library to easy development. It will be interesting to check this DI in more complex projects and compare against other libraries. As for now, I am saying this was the easiest DI I’ve ever done :)

References: