Jan 24, 2016

Setting up Unity Framework in an MVC application

In this blog, let us see how we can set up Unity Framework in our MVC application.

Let us create an MVC application. I would build a simple application where we can view all the employees, add an employee, edit an employee and delete an employee.


If we check the references, we'll find that Unity Framework DLLs are not added by default. So, let's go ahead and add them.
Open up the Package Manager Console(Tools -> NuGet Package Manager -> Package Manager Console) and type the following.
install-package Unity
This will add the following four references to our solution.


We would also need to initialize the container which, in this case, is Unity. For this, let's install another package by using the following command on the Package Console Manager.
install-package Unity.Mvc5
This will add UnityConfig.cs file in the App_Start folder of our application with the following content.

Here, we can see that the UnityContainer is being instantiated. We can register the types and instances in this file. Also, the UnityDependencyResolver is instantiated with the container which has been registered with all the types and instances.

The method RegisterComponents() needs to be called from the Application_Start in Global.asax.cs.




Now, let's do the changes on the MVC side of things.

Let's build our Employee model first and place it in Models folder.

Also, add another file called CompanyDBProvider in the Models folder for reference to the DbContext object.


Let's create a folder for Repositories and add an interface for the repository with the basic functionalities.

Now, let's create the EmployeeRepository which implements all these functions. Below is a snapshot of how we can use the CompanyDBProvider to get the values.



Now, we'll create the EmployeeController with MVC 5 Controller with read/write actions template. There are 3 ways by which we can inject dependencies in Unity as listed below. I prefer constructor injection but let's see all three.
i) Constructor injection - No decoration required.

ii) Property injection - We need to decorate the property with [Dependency] attribute.

iii) Method-call injection - We need to decorate the property with [InjectionMethod] attribute.


Just the last part now, register our newly created component.



Finally, let's test the application.
Run the application, put a breakpoint in the EmployeeController's constructor and hit Employee/Index.


As we can see, EmployeeRepository is being injected into our application by the container(Unity).

Hope this helps.

No comments:

Post a Comment