In this article I will explain with an example, what Dependency Injection is and how to use it in ASP.Net MVC.
In this article, I am making use of Unity package for implementing the Dependency Injection.
What is Dependency Injection?
Dependency Injection (DI) is a fundamental concept in modern software development, promoting the design principle of Inversion of Control (IoC).
Note: The main objective of Inversion of Control (IoC) is to remove the dependencies (remove tight coupling) between the objects of an application which makes the application more decoupled and maintainable.
The Dependency Injection is a process in which, we are injecting the dependent object of a class into a class that depends on that object.
It is the most commonly used design pattern to remove the dependencies between the objects and it allows us to develop loosely coupled software components.
In other words, we can say that Dependency Injection is used to reduce the tight coupling between the software components.
As a result, we can easily manage future changes and other complexities in our application. In this case, if we change one component, then it will not impact the other components.
ASP.Net MVC does not have in-built Dependency Injection.
Download and install Unity Package
ASP.Net MVC does not have in-built Dependency Injection and hence we will need to make use of Unity package for implementing it.
You will need to install the Unity package from
Nuget using the following command.
Install-Package Unity.Mvc5 -Version 1.4.0
Once the package is installed, a success message will be displayed.
Once the package is installed, you will notice UnityConfig.cs class in the App_Start folder of the project
Steps for implementing Dependency Injection
Following are the steps for implementing Dependency Injection in ASP.Net MVC.
1. Create a class and define the methods and inherit it inside the class.
2. Create an Interface and define the methods and inherit it inside the class.
3. Next, register the components i.e. Interface and Class in UnityConfig class.
4. Inject the Interface inside the constructor of Controller.
5. Finally, call the methods using Interface object.
Class
Now, you will need to add new class in the project i.e. Customer class.
The following class inherits the ICustomer Interface and it consists of following method.
GetCurrentDateTime – This method accepts the name as a parameter and a string value is returned which includes the Name and current server Date and Time.
public class Customer : ICustomer
{
public string GetCurrentDateTime(string name)
{
return string.Format("Hello {0}.\\nCurrent Date and Time: {1}", name, DateTime.Now.ToString());
}
}
Interface
Now, you will need to add new Interface in the project i.e. ICustomer which will inherited by the Customer class.
The Interface implements following method of the Customer class.
public interface ICustomer
{
string GetCurrentDateTime(string name);
}
Registering Components
Inside UnityConfig class, you will need to register the components i.e. Interface and Class using RegisterType method of the UnityContainer class as shown below.
public static class UnityConfig
{
public static void RegisterComponents()
{
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>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
container.RegisterType<ICustomer, Customer>();
}
}
Registering UnityConfig Component in Global.asax
Inside the Application_Start event handler, you will need to register the component using RegisterComponents method of the UnityConfig class.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
UnityConfig.RegisterComponents();
}
}
Controller
Inside the Controller, first a private property (Customer) of type ICustomer is created.
Then, the Customer class is injected into the Constructor (HomeController) using the ICustomer Interface using Dependency Injection method.
Finally, the injected object is assigned to the Customer property.
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
This Action method gets called, when Submit Button is clicked and it accepts name as a parameter.
Inside this Action method, the
GetCurrentDateTime method is called where name parameter is passed and returned string value is set into a
ViewBag object.
Finally, the View is returned.
public class HomeController : Controller
{
private ICustomer Customer;
public HomeController(ICustomer customer)
{
this.Customer = customer;
}
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string name)
{
ViewBag.Message = this.Customer.GetCurrentDateTime(name);
return View();
}
}
View
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The View also consists of a TextBox created using Html.TextBox Helper method and a Submit Button.
Submitting the Form
When the
Submit button is clicked, the Form is submitted and the
ViewBag object is checked for NULL and if it is not NULL then, the value of the
ViewBag object is displayed using
JavaScript Alert Message Box.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.TextBox("name")
<input type="submit" value="Submit" />
}
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewBag.Message");
};
</script>
}
</body>
</html>
Screenshot
Downloads