1. Create a new project.
2. Select the template
MVC.
3. Now create a class
Employee.cs and an Interface
Iemployee.cs as shown in the project.
4. Now go to Manage NuGet Package and install
Unity.Mvc3.
After installing we will get two references in our project as follows.
After installing unity we get these two things in the references.
5. Now you will check in the App_start folder you will get a new class file of unity or you can get a file named Bootstrapper.cs.
I have here the Bootstrapper.cs and registering the following interface there as follows.
- private static IUnityContainer BuildUnityContainer()
- {
- var container = new UnityContainer();
- container.RegisterType<IEmployee,Employee>();
-
-
-
-
-
-
- return container;
- }
In the Unity Container I am registering the type Iemployee with Employee class.
6. Go to
global.ascx and register the bootstrapper as follows.
- public class MvcApplication : System.Web.HttpApplication
-
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();
- FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- BundleConfig.RegisterBundles(BundleTable.Bundles);
-
- Bootstrapper.Initialise();
- }
7. Now we are writing one abstract method in the interface and implementing the interface in the class as follows. Here I have written a simple method.
- public interface IEmployee
- {
- string savedata();
- }
8. Now in the Employee class I am implementing the interface and defining the
savedata method.
- public class Employee:IEmployee
- {
-
- public string savedata()
- {
- return "Data Saved...";
- }
- }
Now almost all the work has been finished. Now we will see how to decouple these things.
NOTE: When we are creating an object of a class and calling that class method by its object from another class, then we will say that the two classes are tightly coupled or dependent on each other.
So our aim here is to decouple each class, so here without creating any instance, I will call another class method. Let's see how.
9. In the Home Controller just add the following code:
- public class HomeController : Controller
- {
- IEmployee iemployee;
- public HomeController(IEmployee _iemployee)
- {
- iemployee = _iemployee;
-
- }
So here I am doing a Constructor Injection by creating a constructor and passing the dependency in the constructor.
Now when you try to access the employee class method you can do as follows in another action method.
Here is the code of the screenshot.
- public class HomeController : Controller
- {
- IEmployee iemployee;
- public HomeController(IEmployee _iemployee)
- {
- iemployee = _iemployee;
-
- }
- public ActionResult Index()
- {
- string result= iemployee.savedata();
- return Content(result);
- }
Now just save the program and run. It will produce the following output:
So in this we can see how to implement dependency injection using Unity.
Ream more articles on Design Patterns: