In this article I will explain with an example, what Dependency Injection is and how to use it in ASP.Net using C# and VB.Net.
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
Following are the steps for implementing Dependency Injection in ASP.Net.
1. Install the
Microsoft.Extensions.DependencyInjection package from
Nuget which will be used for implementing the
Dependency Injection.
2. Create a class and define the methods and inherit it inside the class.
3. Create an Interface and define the methods and inherit it inside the class.
4. Create instance of ServiceCollection class and register the service.
5. Initiate the Interface using the GetService method of ServiceProvider object and finally, call the methods using Interface object.
Installing Dependency Injection package using Nuget
You will need to install the Dependency Injection package using the following command.
Install-Package Microsoft.Extensions.DependencyInjection
HTML Markup
The following HTML Markup consists of:
TextBox – For capturing Name.
Button – For displaying Name along with current DateTime.
The Button has been assigned with an OnClick event handler.
<asp:TextBox ID="txtName" runat="server" />
<asp:Button runat="server" Text="Get Current Time" OnClick="OnGetCurrentTime" />
Class
Now, you will need to add new class in the project i.e. CustomerService class.
The following class inherits the ICustomerService 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.
C#
public class CustomerService : ICustomerService
{
public string GetCurrentDateTime(string name)
{
return string.Format("Hello {0}.\\nCurrent Date and Time: {1}", name, DateTime.Now.ToString());
}
}
VB.Net
Public Class CustomerService
Implements ICustomerService
Public Function GetCurrentDateTime(name As String) As String Implements ICustomerService.GetCurrentDateTime
Return String.Format("Hello {0}.\nCurrent Date and Time: {1}", name, DateTime.Now.ToString())
End Function
End Class
ICustomerService
Now, you will need to add new Interface in the project i.e. ICustomerService class.
The Interface implements following method of the CustomerService class.
C#
public interface ICustomerService
{
string GetCurrentDateTime(string name);
}
VB.Net
Public Interface ICustomerService
Function GetCurrentDateTime(name As String) As String
End Interface
Displaying Current Date Time using Dependency Injection
When Get Current Time button is clicked, an object of the ServiceCollection class is created.
Then, the services is registered using AddTransient method to which ICustomerService Interface and CustomerService class is passed.
Next, an object of the ServiceProvider class is created using the BuildServiceProvider method of ServiceCollection object and then, ICustomerService Interface is initialized using GetService method of ServiceProvider class object.
Finally, the
GetCurrentDateTime method is called where TextBox value is passed and returned string value is displayed in
JavaScript Alert Message Box using
RegisterClientScriptBlock method.
C#
protected void OnGetCurrentTime(object sender, EventArgs e)
{
// Create a new ServiceCollection.
ServiceCollection serviceCollection = new ServiceCollection();
// Register the services.
serviceCollection.AddTransient<ICustomerService, CustomerService>();
// Build the ServiceProvider.
ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
// Resolve the service and use it.
ICustomerService customerService = serviceProvider.GetService<ICustomerService>();
string message = customerService.GetCurrentDateTime(txtName.Text);
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('" + message + "');", true);
}
VB.Net
Protected Sub OnGetCurrentTime(sender As Object, e As EventArgs)
' Create a new ServiceCollection.
Dim serviceCollection As New ServiceCollection()
' Register the services.
serviceCollection.AddTransient(Of ICustomerService, CustomerService)()
' Build the ServiceProvider.
Dim serviceProvider As ServiceProvider = serviceCollection.BuildServiceProvider()
' Resolve the service and use it.
Dim customerService As ICustomerService = serviceProvider.GetService(Of ICustomerService)()
Dim message As String = customerService.GetCurrentDateTime(txtName.Text)
ClientScript.RegisterClientScriptBlock(Me.GetType(), "alert", "alert('" & message & "');", True)
End Sub
Screenshot
Downloads