What is Dependency Injection in C#

In this article, we are going to briefly discuss the Dependency Injection in C#. Dependency Injection (DI) is mostly used in complex and real-time applications. But nowadays it’s being normal to use Dependency Injection (DI) in every common application. As a developer, it is compulsory to know why we need Dependency Injection (DI) and what kind of results we can achieve by using it.

Before we jump into “What is Dependency Injection (DI) in C#” we must know that why we need this in our design pattern.

Why do we need Dependency Injection (DI) in C#?

Dependency Injection (DI) is used to achieve loosely coupling in software components. In the other words, it is used to reduce tight coupling in software components and classes. Dependency Injection (DI) helps in modification and changing in complex projects even after completion. This makes a program/Code maintainable and with Dependency Injection (DI) unit test become more convenient.

What is tight coupling in software design?

 In tightly coupled code, one class depends on the other class and if we change the one class which whom the other class depends on the other depending class also must be changed accordingly. It is not difficult to handle if it’s a small application. But it enterprise-level or complex applications must be a headache and difficult to handle.

What is loose coupling in software design?

In loosely coupled software design two objects are independent of each other. If we change one class there is no need to change other ones. Loosely coupled software designs are easy to maintain and enhance in future.

We can achieve this by using Dependency Injection (DI) in the design pattern.

What is Dependency Injection (DI) in C#?

Like it’s obvious by its name Dependency Injection (DI) in the technique of design pattern in which the object of a class is injected into the other class that depends on the injected object. We can change the class of injected object it will not affect the other class. We can maintain our code and application by using Dependency Injection (DI). Inversion of control (IoC) is achieved by implementing Dependency Injection (DI).  It allows the creation of dependency objects outside of a class and provides those objects to a class in a different manner. 

Dependency Injection (DI) involves 3 types of classes.

Client Class: Client class independent class in which depends on Service Class.

Service Class: Service Class is a dependency class that provide service to the client class.

Injector Class: The injection class is a kind of coordinator between the client class and the service class. It injects the service class object into the client class.

As we can see in the above diagram, the Injector is injecting the object of services class into the client class. It separates client class for the creation of the object of service class.

Types of Dependency Injection (DI) with Examples in C#

Constructor Injection:

When the injector injects the dependency object through the client class constructor it’s called constructor injection. Dependency Injection is achieved by injection DEPENDENCY through Client class constructor when creating the instance of that class and injected object can be used anywhere in the class. This method is popular and widely used in the software development industry.

When a class requires more than one dependency it addresses that scenario is the way better approach.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
	  
namespace propertyinjuction  
{  
    public interface text  
    {
        void print();
    }
    class format : text
    {
        public void print()
        {
            Console.WriteLine(" here is text format");
        }      
    }
    // constructor injection
    public class constructorinjection
    {  
        private text _text;
        public constructorinjection(text t1)
        {
            this._text = t1;          
        }
        public void print()
        {  
            _text.print();
        }
    }
    class constructor
    {  
        static void Main(string[] args)
        {  
            constructorinjection cs = new constructorinjection(new format());
            cs.print();
           Console.ReadKey();          
        }
    }
}

Property/Setter Injection:

When the injector injects the dependency object through the client class’s public property. It’s called property or setter injection. But in some scenarios where the requirement is a parameterless constructor so we need to use property injection.

public interface INofificationAction
{      
   void ActOnNotification(string message);
}
   class atul     {  
       INofificationAction task = null;
       public void notify(INofificationAction  at ,string messages)
       {  
       this.task = at;
       task.ActOnNotification(messages);    
       }     
   }
   class EventLogWriter : INofificationAction
   {
       public void ActOnNotification(string message)
       {
           // Write to event log here
       }
   }
   class Program
   {
       static void Main(string[] args)
       {
           //services srv = new services();
           //other oth = new other();
           //oth.run();
           //Console.WriteLine();
           EventLogWriter elw = new EventLogWriter();
           atul at = new atul();
           at.notify(elw, "to logg");
           Console.ReadKey();
       }
   }

Method Injection:

When the injector injects the dependency object through the client class’s public Method. It’s called Method Injection. In method injection, the entire class doesn’t need dependency, Just one method. Constructor Injection is not useful if we only require dependency objects in one or some methods. Because when every time that class is instantiated the dependency object will be created, It will slow the performance of code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
  
namespace propertyinjuction
{  
    public interface Iset
    {
       void print();      
    }
    public class servic : Iset
    {
        public void print()
       {  
            Console.WriteLine("print........");          
        }      
    }
    public class client
    {
        private Iset _set;
        public void run(Iset serv)
        {  
            this._set = serv;
            Console.WriteLine("start");
            this._set.print();
        }      
    }
    class method
    {
        public static void Main()
        {
            client cn = new client();
            cn.run(new servic());
            Console.ReadKey();         
        }
    }
}

Advantages of Constructor Dependency Injection (DI) in C#:

  • Because dependencies are being passed through the constructor so it supports testing.
  • It’s a strong design pattern to achieve a good dependency contract.
  • It increases code maintainability and reusability.
  • It Centralizes code configuration.
  • A good approach to writing a clean code.
  • Encouragement of decoupling

Thank you for reading. Visit Mycodebit.com for .net core and .net tutorial.

Leave a Reply

Related Posts

  • c# Exception Tostring vs Message – Complete Guide

  • c# Yield Exception Handling – Explained!

  • c# Excel Error 0x800a03ec – Complete Guide

  • c# get Error Message from Modelstate – Explained & Solved

  • c# Error Netsdk1005 – Solved!

  • c# Error Parsing Infinity Value – Explained & Solved!