In this article I will explain with an example, how to use Dependency Injection using Microsoft.Extensions.DependencyInjection in ASP.Net MVC.
Downloading Microsoft.Extensions.DependencyInjection package
Steps for implementing Dependency Injection
Following are the steps for implementing Dependency Injection in ASP.Net.
1. Install the
Microsoft.Extensions.DependencyInjection package from
Nuget (Explained earlier) which will be used for implementing the
Dependency Injection.
2. Create a class and define the methods and inherit it inside the class.
3. Then, create a ControllerFactory class and inherit the DefaultControllerFactory class.
4. Next, register the components i.e. Interface and Class inside Global.asax class.
5. Inject the Interface inside the constructor of Controller.
6. 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);
}
Adding Controller Factory
Now, you will need to add new class in the project i.e. MDIControllerFactory class.
The following MDIControllerFactory class inherit DefaultControllerFactory class.
Inside the MDIControllerFactory class, a private property ServiceProvider is declared and set inside the constructor.
Then, the ServiceProvider class is injected into the Constructor (MDIControllerFactory) using Dependency Injection method and the injected object is assigned to the private property Provider.
Then, GetControllerInstance method is overridden which retrieves the Controller instance for the specified request context and controller type.
It accepts the following parameters:
requestContext – The context of the HTTP request, which includes the HTTP context and route data.
controllerType – The type of the Controller.
Finally, ReleaseController method is overridden which releases the specified Controller instance.
ReleaseController method accepts the following parameter:
Controller – The controller to release.
public class MDIControllerFactory : DefaultControllerFactory
{
private readonly ServiceProvider Provider;
public MDIControllerFactory(ServiceProvider provider)
{
this.Provider = provider;
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
IServiceScope scope = this.Provider.CreateScope();
HttpContext.Current.Items[typeof(IServiceScope)] = scope;
return (IController)scope.ServiceProvider.GetRequiredService(controllerType);
}
public override void ReleaseController(IController controller)
{
base.ReleaseController(controller);
IServiceScope scope = HttpContext.Current.Items[typeof(IServiceScope)] as IServiceScope;
scope.Dispose();
}
}
Adding Component in Global.asax
Inside the Application_Start event handler, you will need to add the components i.e. Interface and Class using AddScoped method of the ServiceCollection class as shown below.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
ServiceCollection services = new ServiceCollection();
// Register all your controllers and other services here:
services.AddScoped<HomeController>();
services.AddScoped<ICustomer, Customer>();
var provider = services.BuildServiceProvider(new ServiceProviderOptions
{
// Prefer to keep validation on at all times
ValidateOnBuild = true,
ValidateScopes = true
});
ControllerBuilder.Current.SetControllerFactory(new MDIControllerFactory(provider));
}
}
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 private property Customer.
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 and 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
HTML Markup
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