Dependency Injection in C#

Dependency Injection in C#

Dependency Injection in C#

We are going to learn dependency injection pattern in our application. If you have basic C# knowledge, it is easy to understand. To understand dependency injection pattern, we have to understand what is tight coupling and loose coupling. So, let’s learn same.

  • Tight coupling

Tight Coupling means there is direct use of object of first class in another class to consume the methods of first class. Hence, if we improve first class then we have to put improvement in another class. So, it creates tight coupling of two classes. So, one class is dependent on another class.

  • Loose Coupling

Loosely coupling means two classes are independent of each other.?Hence, if we change in one class then it will not affect another object. Here, we can manage changes easily in future if needed in our application irrespective of its size.??

?????To not make the object of the service class in client classes, we make injector and using this injector’s object we use the method and properties of service class. It fulfils the concept of loose coupling.

No alt text provided for this image

???????????I will explain dependency injection in C# practically using .Net Core Web Application. Open Visual Studio 2019 and Select Create a new project > ASP.NET Core Empty > Add project name > Create.

The above steps are shown below for your convenience.

No alt text provided for this image
No alt text provided for this image

After creating project, you can see the following directory structure in Solution Explorer.

No alt text provided for this image

I will explain both tight and loose coupling practically so you can understand difference between both. Create a Models folder in project. Add a class named Student in this folder.

No alt text provided for this image
No alt text provided for this image

Add properties as shown below in this class.

No alt text provided for this image

Add new service Interface named IStudentRepository in Models Folder which declares methods to be mandatory to implement.

No alt text provided for this image

Declare these methods shown below in this service Interface.

No alt text provided for this image

Now Create this service implementation within the same folder Models and name it StudentRepository. Code is shown below.

No alt text provided for this image

Here We added the DataSource Method to seed the data in this model in the memory.

We started with the empty project template so we need to configure MVC pipeline to run the project. So, add the MVC service in Startup class as shown below.

No alt text provided for this image

Create a new folder named Controllers in same project. Add a Controller class in this folder and name it HomeController (which is by Default).

No alt text provided for this image

Here, we will go for without Dependency Injection means tight coupling. So, we will make the Instance of the service class StudentRepository in Controller to use services of that class. Code is as shown below.

No alt text provided for this image

Run this project. It should give expected output as shown below. You can give parameter in URL to access the other method.

No alt text provided for this image

We can see in above HomeController to get student data, the?HomeController class depends on the?StudentRepository?class. Here, in the HomeController?class, we create an object of StudentRepository?class and then calls the?GetStudentById()?and GetAllStudent. This creates tight coupling because the?HomeController class is now tightly coupled with the?StudentRepository class.

In future if the implementation class of the IStudentRepository is changed then we also need to make changes in the HomeController class as they both are tightly coupled. We can solve this problem by implementing the dependency injection design pattern in our ASP.NET Core Application.

What is Dependency Injection?

The Dependency Injection is a process of injecting the object of a class into another class that depends on it. The Dependency Injection is the mostly used design pattern to remove the dependencies between the classes that allow us to develop loosely coupled software components.

Let’s discuss the required steps procedure to implement dependency injection in ASP.NET Core MVC application.

The ASP.NET Core Framework is designed in such a way that supports Dependency Injection. It injects objects of dependency classes through constructor or method by using a built-in IoC (Inversion of Control) container. We will not dive deep into IoC Container. we just understand how dependency injection works in our application.

To use dependency injection, we have to register service in our Startup class. We can register service in three different methods. These methods will determine the lifetime of the service.

1.???Singleton Method: This method creates an instance of service throughout the application lifetime.

2.???Transient Method: This method creates instance of service as per request.

3.???Scoped Method: This method creates an instance of the service as per request and shared in single request.

We will use Singleton Method to register in Startup class in Configure Method service here. Code as shown below.

No alt text provided for this image

Well now, Service has been registered in Startup.cs??class. We can use this service by injecting object where we want to use. There are three different ways to inject the object.

1.?????Constructor Injection

2.?????Method Injection

3.?????Property Injection

We again, not deep dive into these methods. We will just follow the simple constructor injection. Look at this code given below how the object is injected into constructor. After injection, by using it we can use this to invoke those methods of class.

No alt text provided for this image

We got the same expected result as you can see below.

No alt text provided for this image

Here we got the loosely coupled classes. In future if there is change in the implementation of service interface, we just need to change in that class only not everywhere. By the way, we achieved abstraction which is one of the four concepts of Object-Oriented Programming. ???

You can find the source code form link given below.

https://github.com/kiran-29101999/Dependency-Injection-Demo

?I never thought I can write over any topic or a blog. This, all the credit goes to my company Ansi ByteCode LLP for providing me a platform to share my ideas and thoughts.

Also, I would like to thanks my boss, mentor and manager Hetal Mehta to support me and to put trust on me. I am looking forward to continue collaboration and success with Ansi ByteCode LLP.

Hetal Mehta

CEO @Ansi ByteCode LLP. | .NET - Azure Enthusiast | Microsoft Solution Partners | IAMCP Member | DevOps | Serverless | Cloud-SaaS

2 年

Great Start Kirankumar Bharsadiya

回复
Meghavi Mehta, PHRi

Senior HR Specialist | Employee Relations Specialist | Certified POSH Trainer | Believer of Diversity, Equity, Inclusion, & Belonging

2 年
回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了