Dependency Injection in C# (2023)

This article explains how to implement Dependency Injection in C# and .NET. 

Dependency Injection (DI) is a software design pattern that helps developers build better software. It allows us to develop loosely-coupled code that is easy to maintain. Dependency Injection reduces the hard-coded dependencies among your classes by injecting those dependencies at run time instead of design time technically.

Dependency Injection CSharp 

We have the following ways to implement Dependency Injection. 

Constructor Injection in C#

Construction injection is the most commonly used dependency pattern in Object Oriented Programming. The constructor injection typically has only one parameterized constructor, so in this constructor dependency, there is no default constructor, and we need to pass the specified value at the time of object creation. We can use the injection component anywhere within the class. It addresses the most common scenario where a class requires one or more dependencies.

The following is an example:

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();          
        }
    }
}

Dependency Injection in C#

The builder assembled the dependencies bypassing the services that implemented the text interface.

Property Injection in C#

We use constructor injection, but there are some cases where I need a parameter-less constructor, so we need to use property injection.

The following is an example:

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();
       }
   }

You cannot control when the dependency is set at all. It can be changed at any point in the object's lifetime. 

Method Injection in C#

In method injection, we only need to pass the dependency in the method. The entire class does not require dependency, just one method. I have a class with a method that has a dependency. I do not want to use constructor injection because then I would create the dependent object every time this class is instantiated, and most of the methods do not need this dependent object.

The following is an example:

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();         
        }
    }
}

Dependency Injection in C#

Summary

This article helps reduce class coupling, increase code reuse, improve code maintainability, improve application testing, and help easily do unit testing. In this article, with code samples, we saw some use cases of dependency injection using C# and .NET.

Next: Dependency Injection In ASP.NET MVC

 


Recommended Free Ebook
Similar Articles