In this article I will explain with an example, what Dependency Injection is and how to use it in ASP.Net Core MVC (.Net Core 6).
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.
Steps for implementing Dependency Injection
1. Create a class and define the properties and methods.
2. Create an Interface and define the methods and inherit it inside the class.
3. Next, registering the dependency i.e. Interface and Class in service container inside Program.cs class.
4. Inject the class using its Interface inside the constructor of Controller.
5. Finally, call the class methods by creating an object of Interface.
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 class.
The Interface implements following method of the Customer class.
public Interface ICustomer
{
string GetCurrentDateTime(string name);
}
Registering Dependency Service in Program.cs
Open the Program.cs file and inside Program.cs class, you will need to register dependency i.e. Interface and Class in service container using AddScoped method of the Services class.
using Dependency_Injection_Core.Models;
using Dependency_Injection_Core.Models.Interface;
var builder = WebApplication.CreateBuilder(args);
// Enabling MVC.
builder.Services.AddControllersWithViews();
// Registering Dependency Service
builder.Services.AddScoped<ICustomer, Customer>();
var app = builder.Build();
//Configuring Routes
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
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 using the
Customer property and name parameter is passed and returned string value is set into a
ViewBag object.
Finally, the View is returned.
public class HomeController : Controller
{
private readonly ICustomer Customer;
public HomeController(ICustomer customer)
{
this.Customer = customer;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(string name)
{
ViewBag.Message = this.Customer.GetCurrentDateTime(name);
return View();
}
}
View
HTML Markup
Inside the View, first the ASP.Net TagHelpers is inherited.
The View consists of an HTML Form which has been created using the ASP.Net TagHelpers with the following attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The following HTML Form consists of a TextBox 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.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post" asp-controller="Home" asp-action="Index">
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewBag.Message");
};
</script>
}
</body>
</html>
Screenshot
Downloads