Downloadable source code

Dependency is just another object that a class needs to do its function.
For example, Main program calls a Service class lets say “Customer Class” to update a customer profile. The Customer class generate the required data and creates an instance of Database operations layer (Let’s say “CustomerOperations class”) to update the database tables. In this example, Customer class is dependent on CustomerOperations class to update a customer profile or CustomerOperations class is the dependency of Customer Class.


The problem with this classic way of creating dependencies and consuming them is it creates a tightly coupled program, over the time the program will grow into a spaghetti code. Additionally, a tightly coupled program is not flexible to work with efficient programming styles like Test-Driven development (TDD) because in order to unit test our customer class, we will always need a fully functioning CustomerOperations and database tables. We cannot unit test the code without touching data in Database. Or Cannot mock the database operations.

Dependency injection means, all the dependencies are created outside of the consuming application and pushed into it by the creator of class and its dependency. In our example application, the main program will create the implementation of ICustomerOperations and pass it on to the Customer class while it invokes customer class. The customerOperations class then use the implementation provided by injected dependency to update customer data.

Dependency injection creates a loosely coupled program and it allows developers to do mock texting.

In ASP.Net the controllers are created by ASP.NET Controller Factory. The default behavior of controller factory does not allow injecting dependencies into the controller. In order to force controller factory to inject a dependency, we have to extend IControllerFactory. Or we can use IoC containers like Microsoft Unity or Ninject.

Step 1: Create a new ASP.Net MVC program


Step 2: Add Microsoft Unity NuGet package into references
Expand Project in visual studio solution explorer, right click on references and select “Manage Nuget packages”.
Search for Unity.MVC and install the latest version.

After Unity.MVC installed, expand the App_Start folder and verify UnityConfig.cs and UnityMvcActivator.cs are created.
Step 3: Add a new controller “HomeController.cs” into Controllers folder

Step 4: Add a new Interface “IGreetingService.cs” into the root project folder and modify its content as below

namespace Customer
{
    public interface IGreetingService
    {
        string GetGreeting();
    }
}

Step 5: Add a new class “GreetingService.cs” into the root project folder and modify its content as below

namespace Customer
{
    public class GreetingService : IGreetingService
    {
        public string GetGreeting()
        {
            return "Hello there how are you";
        }
    }
}

Step 6: Add a contructor into HomeController and modify HomeController as below

using System.Web.Mvc;
namespace Customer.Controllers
{
    public class HomeController : Controller
    {
        private IGreetingService _greetingService;
        public HomeController(IGreetingService greetingService)
        {
            _greetingService = greetingService;
        }
        public ActionResult Index()
        {
            return Content(_greetingService.GetGreeting());
        }
    }
}

Step 7: Rebuild and run the project.
You will get an error page this is because we have not configured Unity to inject the GreetingService when HomeController is created.

Step 8: Modify App_Start > UnityConfig.cs to include Bindig for IGreetingService

public static void RegisterTypes(IUnityContainer container)
{
    container.RegisterType<IGreetingService, GreetingService>();
}

Step 9: Rebuild and run the project.

Now the GreetingService dependency is injected into HomeController when it is created, and HomeController can use the injected implementation to get the greeting message from it.