Dependency injection in C#

What is Dependency Injection?

Dependency Injection (DI) is a software design pattern. It allows us to develop loosely-coupled code. How does it do that? 


DI reduces the hard-coded dependencies among your classes by injecting those dependencies at runtime/compile time instead of design time technically. Thus it reduces the tight coupling among different software components.

It also helps in improving the code readability and testability. Now we know that there quite a lot of advantages using Dependency injection, lets go ahead and identify how many different kinds of Dependency injections are there and how do we go about implementing them.

Constructor Injection

This is most commonly used dependency injection pattern in object oriented programming. The constructor injection normally 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.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
  
namespace propertyinjection  
{  
    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 Injection

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 method injection, we need to pass the dependency in the method only. The entire class does not need the dependency, just the 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 be creating 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();  
          
          
        }  
    }  
} 

Using Dependency injection like the scenarios mentioned above gives you flexibility and loosely coupled code, better control to write API testing or unit testing and makes the code cleaner and understandable.

Please share your views on the same either by commenting to this post or you can also drop me an email at naik899@gmail.com

The post Dependency injection in C# appeared first on Ravindra Naik.

Comments

Popular posts from this blog

Serve GZip CSS and JS from AWS S3

Create a Central Logging System

Create a calendar invite (ics file) in ASP NET