Tuesday, August 5, 2014

Inversion of Control ( IoC ) Container - Step by step how to add to an MVC Application

In this article we'll see how to add an Inversion of Control ( IoC ) Container to an Asp.Net MVC Application , applying the Dependency Injection pattern.
In this tutorial we'll be using the Unity Application Block (Unity) container . This IoC container will allow us to perform a  dependency injection in our Controller class , in order to achieve a fully decoupled software design of our MVC App.
MVC loosely coupled applications are flexible, easy to test and easier to maintain.
Building loosely coupled applications means minimizing or just nullifying the dependencies between software objects. In our example, our Controller will have not knowledge at all of the Data Repository, and viceversa, and that means that we can in the future alter each one of them with no consequences for the other.The data will be displayed in the View as follows :




The complete documentation for the Unity open source software resides in Codeplex. It also includes a FREE ebook for you to deep in the issue:


When we talk about Inversion of Control we intend to express that instead that we control the data framework instantiating it in our Controllers, THE FRAMEWORK CONTROLS our controllers code by injecting itself into them. We don't initialize the framework, but it is alive and search the controllers in order to inject itself there. Then, when we come to test our MVC, we don't have to access the database because we don't have the framework constructor inside our controllers anymore. We can inject into them any test framework we want.
There are many IoC Containers, such as Castle Windsor, Spring.Net, Ninject and Unity by Microsoft. We are going to use this later.

The complete step by step stages for adding an IoC container to your MVC application are the following:

1) Install the Unity Block container using NuGet
2) Add an Unity Container .cs file (provided by the NuGet package) containing the code to build the container
3) Register your Data Repository type inside that code (in the BuildUnityContainer() method)
4) Setup the IoC Container in the Global.asax (calling the Initialize() method)
5) Inject the dependency in your Controller


1) Install the Dependency Injection Container using NuGet

Open the NuGet Manager and search for "Unity.MVC4", then install the package :


The package includes 2 assemblies and the "Bootstrapper" Container code file:



2) Add an Unity Container .cs file (provided by the NuGet package) containing the code to build the container 

This file is habitually provided in that package , but if don't, just create a .cs file with this code:


namespace IoCDependencyInjection
{
public static class IoC
{
public static IUnityContainer Initialise()
{
var container = BuildUnityContainer();

DependencyResolver.SetResolver(new UnityDependencyResolver(container));

return container;
}

private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();

// register all your components with the container here
// it is NOT necessary to register your controllers

// e.g. container.RegisterType<itestservice testservice="">();
container.RegisterType<INotesRepository, NotesRepository>(); 

RegisterTypes(container);

return container;
}

public static void RegisterTypes(IUnityContainer container)
{

}
}
}


(I changed the class name to "IoC")

3) Register your Data Repository type inside that code (in the BuildUnityContainer() method)

Then uncomment the code lines inside the BuildUnityContainer() method , and insert the Repository Interface and Class types:




// e.g. container.RegisterType<ITestService, TestService>();        container.RegisterType<INotesRepository, NotesRepository>();  

4) Setup the IoC Container in the Global.asax (calling the Initialize() method)





5) Inject the dependency in your Controller






private INotesRepository Repository;
        public IoCTestingController(INotesRepository rep)        {            Repository = rep;        }

That's all respecting to Dependency Injection & Inversion of Control.


Now, in order to finish building the MVC app, we need a Data Repository and a Controller with its Views.
First we'll need a Repository working on an XML file to store the data in, so build it with the code you'll find in this Building Block.

You'll also find there a small XML file to include in your application.

Now for the Controller, these are the methods using the Dependency Injection that we created :

CRUD OPERATIONS : 


CREATE :



RETRIEVE :




UPDATE :



DELETE :






After you finish your application , browse to the Views to see the List, Details, Edit & Delete screens:






If you liked the look of this site, learn how to create it using open source CSS templates in this tutorial.

That's all!!  In this tutorial we've learned how to add an Inversion of Control ( IoC ) Container to an Asp.Net MVC Application , applying the Dependency Injection pattern.
Happy programming.....
        By Carmel Schvartzman
כתב: כרמל שוורצמן