Dependency Injection In C#

Rate this post

Dependency Injection in C# is a part of Design patterns in programming languages like C# and it helps us in writing clean code. In this article, we will be going to know this Dependency Injection completely from start to end i.e. why dependency injection is introduced in programming and what are its benefits and many more. So hock till the end of this article and get all the understanding from me. Let’s get started.

Dependency Injection

Dependency Injection is a combination of two different terms, Dependency and Injection and it simply means that we use it for injecting some dependency in programs to achieve our intended work. So let’s understand it one by one.

What is dependency? what is coupling?

As we know, whenever we create classes in any programming language we cannot declare every required thing in just one class, because it may lead to redundant code which may not be scalable in the future or it leads to code maintenance every time. For Example: there is a class Person in c# and this class has some properties like name, height, weight, color, etc., and has some methods like walking, seating, and speaking but at the same time, this person is also dependent on Home, Hospital, and some other things and we cannot declare the whole functionality of this in same Person’s class. Therefore, whenever we instantiate other courses in the intended class it is called a dependency like the Person class is dependent on the Home class. This will make sense if you look into below code block.

Class Person{
    private Home _home;
    private School _school;
    private Hospital _hospital;
    public Person(){                 // contructor class for person
       _home = new Home();  // as we can see there is an initiation of Home class in person.
       _school = new School();
       _hospital = new Hospital();
    }
    public void TakeRefuge()
{
      _home.ProvideShelter(this);
    }
}

In the above code, we can see Person class is dependent on the Home(), School(), and Hospital() classes which is why these class objects are instantiated. and once any class is dependent on any other classes they do coupling with each other which further means that they will use their properties and methods at compile time.

Note: all the bold text denotes class names and we can assume that it is already declared somewhere.

Relation between dependency and coupling.

In the programming world, I am damn sure that you already have heard that program is kind of loosely coupled or tightly coupled and still you don’t know these terms very well, Don’t worry I have all the examples that can clear your doubts and misconception.

Whenever any class is dependent on another class in C# they simply do coupling to achieve the intended out i.e if a Person is somehow injured then he uses the facility of the Hospital to heal up and become normal and healthy again, So here coupling happens between Person class and Hospital class. One more point is that the Relation between Dependency and Coupling is higher the dependency in coding means that the code is highly coupled and if the dependency is low then the code is Loosely coupled.

Why is coupling bad?

Due to tightly coupled code, there is a drastic increase in code maintenance, and code refactoring which in turn results in to increase in the development cost, for example in the above-shared code block of a Person class we have instantiated Home, Hospital, and School directly in the constructor and if in the future we want to change the name of education type School from Tution, as both are used for education purpose, and due to direct initialization in constructor then we need to replace School with Tution in every place in Person’s class which lead to higher code maintenance. So to minimize this type of coupling we need to implement dependency injection in our code.

What is dependency injection?

Dependency Injection is a design pattern used for minimizing coupling in programming languages. In Dependency Injection, we use multiple ways to minimize coupling to some extent and here I want to take you on a journey from the initial level of dependency injection to the advanced level of dependency injection and this will make sense and boost your understanding in the field of dependency injection.

Types of Dependency Injection:

There are majorly three types of dependency injection in the design pattern which are as follows and we see each in detail one by one.

  1. Constructor Injection.
  2. Property Injection.
  3. Method Injection.

1. Constructor Injection.

Dependency Injection says instead of direct initialization of classes like Home, Hospital, and School in Persons class like in the above code block pass that complete object as a parameter in a constructor class which means that anyone initiating that class will provide that object by initiating it in there class and therefore we can call it as Constructor Injection. Refer to the below-modified code block for a better understanding.

Class Person{
    private Home _home;
    private School _school;
    private Hospital _hospital;
   //As all the dependencies are passed in the constructor class means constructor dependency injection
    public Person(Home home, School school, Hospital hospital){ 
       _home = home;  
       _school = school;
       _hospital = hospital;
    }
    public void TakeRefuge()
{
      _home.ProvideShelter(this);
    }
}
public class Program{
 
    static void Main(string[] args){
     
         Home home = new Home();
         Person person = new Person(home);
         person.TakeRefuge();
   }
}

In code block, instead of initiating Home, Hospital, and School objects in the Person class, we are using objects provided as parameters in the constructor class i.e from Program we are instantiating Person object by passing the required parameter/object while initiating it as shown in above code is known as Contructor Injection.

Property Injection

In Property Injection, we use dependencies by declaring a property in the dependent class. for example, if we want to use the School class in the Person class using property injection then we need just declare it as a property at the start instead of passing it as the parameter. Refer to the below code block for better understanding.

Class Person{
    private Home _home;
    private School _school;
    private Hospital _hospital;
 
   public School School{
             set
             {
                 _school = value;    
              }
    }  // property injection
   //As all the dependencies are passed in the constructor class means constructor dependency injection
    public Person(Home home, Hospital hospital){ 
       _home = home;  
       _hospital = hospital;
    }
    public void TakeRefuge()
    {
      _home.ProvideShelter(this);
    }
    public void Study()
    {
      if(_school != null)                          //null check for school variable.
             _school.Teach(this);
    }
    public void GetTreatment()
    {
      _hospital.cure(this);
    }
}
public class Program{
 
    static void Main(string[] args){
     
         Home home = new Home();
         Person person = new Person(home);
         person.School = new School();
         person.Study();
         person.TakeRefuge();
         person.GetTreatment();
   }
}

In the above code, we are declaring School using property injection in the person’s class and we can use it with Person’s objects by initiating it as shown above. Here we also need to take care that the School object is not declared previously as it is public and to check that we use the null check in the method before using its variable in the person’s class.

Do you know you can find more such articles at CodeWithDC.

Method Injection

Method injection is used when the dependency is only used in one method and not required in other methods. To implement Method Injection we can provide dependency directly in the method needing it as a parameter. for example: a person use to go home and school in their daily life and in rare occasions person needs to go Hospital for a cure which means that in Person’s class instead of doing constructor injection for Hospital dependency we will implement Method Injection as shown below.

Class Person{
    private Home _home;
    private School _school;
    private Hospital _hospital;
 
   public School School{
             set
             {
                 _school = value;    
              }
    } 
    public Person(Home home){ 
       _home = home;  
    }
    public void TakeRefuge()
    {
      _home.ProvideShelter(this);
    }
  public void GetTreatment(Hospital hospital)            //Method Injection
    {
      hospital.cure(this);
    }
}

After using these three types of dependency injection, the coupling has been reduced to some extent and still we can reduce it by implementing interfaces in c#. Because Interfaces give us the flexibility to manage all the dependencies in one place and provide them to called classes by using frameworks like Autofac Containers. Although we can implement Dependency Injection without using Interfaces and using interfaces can add more flexibility into it and this leads to loosely coupled code. For example, School is a type of education and in the future a person can shift from school to tuition, So using the interface for this will be helpful because we can change that dependency using only one change as shown below.

public interface IEducationalInstitution{
void Teach(Person person);
}
public class College : IEducationalInstitution{
           public void Teach(Person person){
                          Console.WriteLine("Educate person in school");
          }
}
public class School : IEducationalInstitution{
           public void Teach(Person person){
                          Console.WriteLine("Educate person in school");
          }
}
//till here EducationalInstitution interface is declared and School class implements this interface
//So whenever this interface is initiated with School object then user can use School class funcitionalities
//below is the modified version of Person Class with this interface.
Class Person{
    private Home _home;
    private IEducationalInstitution _school;
    private Hospital _hospital;
 
   public IEducationalInstitution School{
             set
             {
                 _school = value;    
              }
    } 
    public Person(Home home){ 
       _home = home;  
    }
    public void TakeRefuge()
    {
      _home.ProvideShelter(this);
    }
  public void GetTreatment(Hospital hospital)            //Method Injection
    {
      hospital.cure(this);
    }
}
//now if we want to use College as educational type then we need to just replace School with College in //Main Method as shown below
public class Program{
 
    static void Main(string[] args){
     
         Home home = new Home();
         Person person = new Person(home);
         person.School = new College();
         person.Study();
         person.TakeRefuge();
         person.GetTreatment();
   }
}

Refer to comments in the code block for better understanding.

How does dependency injection reduce coupling?

Using dependency injection we are not making a class completely dependent on any other classes instead we are making it free to choose in EducationInstitution, two classes implement this interface i.e School and College and if in the future a person wants to go with College as education then he didn’t need to change school with college instead we ask interface by passing College instance and EducationInstitution will provide all the college functionality and that’s how dependency injection helps in reducing coupling or we can say that our code is loosely-coupled.

Leave a Comment

Scroll to Top