Dependency Injection in C#

This article I am going to explain how to implement Dependency Injection in C#. Dependency Injection (DI) is a software design pattern that allows us to develop loosely coupled code in our project.

What is Dependency Injection in C#?

DI is a great way to reduce tight coupling between software components. The purpose of DI is to make code maintainable it also enables us to manage future changes in better way and also helps to manage other complexities in our software.

Let’s discuss this with the help of example:

Suppose that class A invokes a method on class B, which subsequently invokes a method on class C. This implies that A is reliant on B, and B is reliant on C. By employing dependency injection, we can supply an instance of class C to class B, and provide an instance of B to class A, rather than requiring these classes to create the instances of B and C themselves.

Dependency Injection types:

Dependency injection is of three types as given below:

  • Constructor Injection
  • Property Injection
  • Method Injection

Constructor Injection in C#:

Construction injection is the most commonly used dependency pattern in Object Oriented Programming. This technique usually involves a constructor that takes parameters. Therefore, there is no default constructor in this dependency pattern, and we must provide the designated value during object instantiation. We can utilize the injection component in any section of the class where we will need it. It deals with the typical situation where a class necessitates one or more dependencies.

Code sample of constructor Injection:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CtorInjectionSample
{
    public interface text
    {
        void printme();
    }
    class formatInput : text
    {
        public void printme()
        {
            Console.WriteLine(" This is constructor Injection");
        }
    }
    // constructor injection
    public class constructorinjection
    {
        private text _text;
        public constructorinjection(text t1)
        {
            this._text = t1;
        }
        public void printme()
        {
            _text.printme();
        }
    }
    class constructor
    {
        static void Main(string[] args)
        {
            constructorinjection csi = new constructorinjection(new formatInput ());
            csi.print();
            Console.ReadKey();
        }
    }
}

Property Injection in C#

Although constructor injection is very popular and it is used widely, but there are some cases where we need a parameter-less constructor in our program, in that case we need to use property injection. Let’s see below with the help of example how we can implement it.  

public interface iNofificationActor
{
   void ActionOnNotification(string mesg);
}
  Public  class MySample     {
       iNofificationActor task = null;
       public void notify(iNofificationActor  at ,string message)
       {
       this.task = at;
       task. ActionOnNotification(messages);
       }
   }
   class EventLogWriter : iNofificationActor
   {
       public void ActOnNotification(string message)
       {
           // you can write to event log here
       }
   }
   class Program
   {
       static void Main(string[] args)
       {
           
           EventLogWriter elwr = new EventLogWriter();
           MySample     at = new MySample();
           at.notify(elwr, "My sample logs ");
           Console.ReadKey();
       }
   }

Method Injection in C#

When using method injection, we simply pass the necessary dependency as an argument to the method, rather than requiring it for the entire class. In my particular scenario, I possess a class that contains a single method which relies on a specific dependency. I prefer not to utilize constructor injection since it would entail creating the dependent object every time the class is instantiated, which is unnecessary for the majority of the other methods within the class. Let’s see and understand it using code sample below.

namespace propertyinjuction
{
    public interface Iset
    {
        void print();
    }
    public class TestService : Iset
    {
        public void print()
        {
            Console.WriteLine("Method Injection in C#.");
        }
    }
    public class clients
    {
        private Iset _set;
        public void run(Iset serv)
        {
            this._set = serv;
            Console.WriteLine("start printing from here….");
            this._set.print();
        }
    }
    class method
    {
        public static void Main()
        {
            clients c = new clients();
            c.run(new TestService());
            Console.ReadKey();
        }
    }
}

In this post we learn about “Dependency Injection in C#” and all its three types. It will help to reduce class coupling and increase code reusability and will improve code maintainability as well. You can read such content here or can check more such article in our C# Section.

Leave a Reply

Your email address will not be published. Required fields are marked *