Constructor Dependency Injection Pattern Implementation in C#

Introduction

Dependency Injection (DI) is a pattern where objects are not responsible for creating their own dependencies. Dependency injection is a way to remove hard-coded dependencies among objects, making it easier to replace an object's dependencies, either for testing (using mock objects in unit test) or to change run-time behavior.

Before understanding Dependency Injection you should be familiar with the two concepts of Object Oriented Programming, one is tight coupling and another is loose coupling, so let's see each one by one.

Tight Coupling: When a class is dependent on a concrete dependency, it is said to be tightly coupled to that class. A tightly coupled object is dependent on another object; that means changing one object in a tightly coupled application often requires changes to a number of other objects. It is not difficult when an application is small but in an enterprise level application it is too difficult to make the changes.

Loose Coupling: It means two objects are independent and an object can use another object without being dependent on it. It is a design goal that seeks to reduce the inter- dependencies among components of a system with the goal of reducing the risk that changes in one component will require changes in any other component.

Now in short, Dependency Injection is a pattern that makes objects loosely coupled instead of tightly coupled. In this article you will be the first to introduce tight coupling and thereafter you will introduce loose coupling using the Constructor Dependency Injection Pattern. So let's see that.

Using the Code

To understand the concept of Dependency Injection, create an example that is the Error Log Management. The Error Log Management example describes how to create an error log for the application. There are two types of log management, one is using a text file and the other is uses an event viewer.

First of all create an interface IErrorLogger that has one method to write the error log. This interface will be inherited by other log classes.

  1. using System;  
  2.   
  3. namespace DependencyInjection  
  4. {  
  5.     public interface IErrorLogger  
  6.     {  
  7.         void LogMessage(Exception ex);  
  8.     }  
  9. }  
Now create a class, FileLogger class, that inherits the IErrorLogger interface. This class writes an error log message to a text file.
  1. using System;  
  2. using System.Configuration;  
  3. using System.IO;  
  4.   
  5. namespace DependencyInjection  
  6. {  
  7.     public class FileLogger : IErrorLogger  
  8.     {  
  9.         public void LogMessage(Exception ex)  
  10.         {  
  11.             string folderPath = ConfigurationManager.AppSettings["ErrorFolder"];  
  12.             if (!(Directory.Exists(folderPath)))  
  13.             {  
  14.                 Directory.CreateDirectory(folderPath);  
  15.             }  
  16.             FileStream objFileStrome = new FileStream(folderPath + "errlog.txt", FileMode.Append, FileAccess.Write);  
  17.             StreamWriter objStreamWriter = new StreamWriter(objFileStrome);  
  18.             objStreamWriter.Write("Message: " + ex.Message);  
  19.             objStreamWriter.Write("StackTrace: " + ex.StackTrace);  
  20.             objStreamWriter.Write("Date/Time: " + DateTime.Now.ToString());  
  21.             objStreamWriter.Write("============================================");  
  22.             objStreamWriter.Close();  
  23.             objFileStrome.Close();  
  24.         }  
  25.     }  
  26. }  
Now create a class EventViewerLogger class that inherits the IErrorLogger interface. This class writes an error log message in the event viewer.
  1. using System;  
  2. using System.Configuration;  
  3. using System.Diagnostics;  
  4.   
  5. namespace DependencyInjection  
  6. {  
  7.     public class EventViewerLogger : IErrorLogger  
  8.     {  
  9.         public void LogMessage(Exception ex)  
  10.         {  
  11.             EventLog objEventLog = new EventLog();  
  12.             string sourceName = ConfigurationManager.AppSettings["App"];  
  13.             string logName = ConfigurationManager.AppSettings["LogName"];  
  14.             if (!(EventLog.SourceExists(sourceName)))  
  15.             {  
  16.                 EventLog.CreateEventSource(sourceName, logName);  
  17.             }  
  18.             objEventLog.Source = sourceName;  
  19.             string message = String.Format("Message: {0} \n StackTrace: {1} \n Date/Time: {2} ", ex.Message, ex.StackTrace, DateTime.Now.ToString());  
  20.             objEventLog.WriteEntry(message, EventLogEntryType.Error);  
  21.         }  
  22.     }  
  23. }  
Now we create another class to understand the concept of tight coupling. The Operation class has an interface, an IErrorLogger instance, created by the FileLogger class. In other words the Operation class object is tightly coupled with the FileLogger class.
  1. using System;  
  2.   
  3. namespace DependencyInjection  
  4. {  
  5.    public class Operation  
  6.     {  
  7.        IErrorLogger logger = new FileLogger();  
  8.        public void Division()  
  9.        {  
  10.            try  
  11.            {  
  12.                int firstNumber = 15, secondNumber = 0, result;  
  13.                result = firstNumber / secondNumber;  
  14.                Console.WriteLine("Result is :{0}", result);  
  15.            }  
  16.            catch (DivideByZeroException ex)  
  17.            {  
  18.                logger.LogMessage(ex);  
  19.            }  
  20.        }  
  21.     }  
  22. }  
The code above works, but it's not the best design because it is tightly coupled with FileLogger. When you want to use another IErrorLogger implementation class then you need to change it. That is not depending on the Open Closed Principle of Object Oriented Programming.

Now call your class method in your application startup class and you get a log in the text file so your start up class code is below.
  1. using System;  
  2. namespace DependencyInjection  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             Operation objOperation = new Operation();  
  9.             objOperation.Division();  
  10.             Console.Read();  
  11.         }  
  12.     }  
  13. }  
Let's run the application. You will get an exception in the log file such as in Figure 1.1.

 


Figure 1.1 Error Log in txt File

To solve this problem you should use constructor dependency injection in which an IErrorLogger is injected into the object.

Constructor Dependency Injection Pattern

This is the most commonly used Dependency Pattern in Object Oriented Programming. The Constructor Injection uses a parameter to inject dependencies so there is normally one parameterized constructor always. So in this constructor dependency the object has no default constructor and you need to pass specified values at the time of creation to initiate the object.

You can say that your design is loosely coupled with the use of constructor dependency injection.

Now create a class OperationEvent. That class has a parameter constructor. This constructor will be used to inject dependencies in the object. Let's see the following code.
  1. using System;  
  2.   
  3. namespace DependencyInjection  
  4. {  
  5.     public class OperationEvent  
  6.     {  
  7.         IErrorLogger logger;  
  8.   
  9.         public OperationEvent(IErrorLogger logger)  
  10.         {  
  11.             this.logger = logger;  
  12.         }  
  13.   
  14.         public void Division()  
  15.         {  
  16.             try  
  17.             {  
  18.                 int firstNumber = 15, secondNumber = 0, result;  
  19.                 result = firstNumber / secondNumber;  
  20.                 Console.WriteLine("Result is :{0}", result);  
  21.             }  
  22.             catch (DivideByZeroException ex)  
  23.             {  
  24.                 logger.LogMessage(ex);  
  25.             }  
  26.         }  
  27.     }  
  28. }  
By the preceding you have noticed that an OperationEvent object is neither dependent on an FileLogger object nor an EventViewerLogger object so you can inject either FileLogger dependencies or EventViwerLogger dependencies at run time. Let's see the startup class in which we inject EventViwerLogger dependencies in an OperationEvent object using constructor dependency injection.
  1. using System;  
  2.   
  3. namespace DependencyInjection  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             OperationEvent objOperationEvent = new OperationEvent(new EventViewerLogger());  
  10.             objOperationEvent.Division();  
  11.             Console.Read();  
  12.         }  
  13.     }  
  14. }  
Let's run the application and you get the results as in Figure 1.2 .


Figure 1.2 Log Errors in Event Viewer.

Conclusion

This article has introduced a basic object oriented concept such as tight coupling and loose coupling. I hope you also get an idea of how to manage your application error log and finally you have learned about Constructor Dependency Injection Pattern. I hope it will be helpful for you and if you have any doubt or feedback then post your comments here or you can directly connect to me by https://twitter.com/ss_shekhawat.


Similar Articles