Dependency Injection(DI) In C#

Kailash Chandra Behera | Wednesday, October 12, 2016

Introduction

This article explings the problem of tight coupling, demonstrates how to use Dependency Injection(DI) in c# and its use.

Getting Started

Have you thought about or create any property inside your class that does not depends on any particular type. The answer might be "No", but don't worry Dependency Injection(DI) will fulfill your requirements.

Dependency Injection(DI) is a special type of design pattern, that enables to create loosely coupled classes, it is a great way to reduce tight coupling.

For example let's say there are two classes Class A and Class B and ClassA uses ClassB by creating property inside it like below code example, they are joined together as an aggregation and are tightly coupled.

 
//concept of tight coupling
public class ClassA  
 {  
   public ClassB classB { get; set; }  
 }  
 public class ClassB  
 {  
 }  

You cannot pass the object of other class rather than ClassB to ClassA's property class B, Because of tightly coupled, When two classes are tightly coupled, they are linked with a binary association.

I am sure you might have thought that loosely coupled can be achieved by using Interface, so why there is need of Dependency Indection. Yes loosely coupled can be created with the help of Interface like below code example.
 public class ClassA  
 {  
   public IClass lcoupled{ get; set; }  
 }  
 public interface IClass  
 {  
 }  
 public class ClassB : IClass  
 {  
 }  
ClassA has reference to interface IClass instead of a direct binary reference to ClassB and achieved loosely coupled. However, this implementation of loose coupling presents a problem.

If ClassA is responsible for creating a new instance of ClassB, you only have the illusion of being loosely coupled because ClassA must still know about ClassB. This is shown in the bolow code.
 public class ClassA 
 {  
   public ClassA()  
   {  
     ClassB = new ClassB();        
   }  
   public IClass lcoupled{ get; set; }  
 }  
 public interface IClass   
 {  
 }  
 public class ClassB : IClass  
 {  
 }  
In the above illustration because of constructor, ClassA is still tightly coupled to ClassB.

The solution for above discussioned problem is Dependeny Injection(DI). A third class DependencyFactory that resolves the dependencies eliminates the last bit of tight coupling. The below code uses Dependeny Injection to implement loose coupling.
 public class ClassA  
 {  
   public readonly IClass _classb;  
   public ClassA():this(DependencyFactory.Resolve<IClass>())  
   {  
   }  
   public ClassA(IClass classb)  
   {  
     _class2 = class2;  
   }  
 }  
 public interface IClass   
 {  
 }  
 public class ClassB : IClass  
 {  
 }  

Summary

Mostly Dependency Injection(DI) is useful for unit testing, validation and exception management. Hope this article may helpful to you

Thanks