Continuing in my series of articles related to concept of dependency injection and methods to implement the same, now we will discuss how we can implement the dependency injection. if you would like to begin from the basic, then i would recommend you to read my first article.
As we discussed earlier that we can implement dependency injection in 3 different ways, in this article, we will discuss the concept of constructor injection, to supply the dependency to a dependent component.
To start with, we will have a common interface ILogger, with method named LogInfo. Two classes, TextLogger and XMLLogger will implement this interface and with their own code of logging the info. In our example, we will simply print the info received. So our initial code setup will be :
Next, we have a class User. This class will have a parameterized constructor, where the parameter will be an interface instance. Apart from the constructor, this class will be having two methods, one is SaveData and other is DeleteData. Both these methods will be using this logger instance to perform the logging process. Finally client code will call the User class methods using 2 instances _user1 and _user2, with two different logger types received in the constructor of the class. See the code below :
Run the code. When the methods are called with _user1 instance, the _iLogger instance contains reference of the TextLogger class. So when the methods SaveData & DeleteData are called, LoggerInfo of Textlogger is called. Similarly, for _user2 case, XMLLogger is used for logging. See the results below :
Very easy to implement. So this is how we implement the dependency injection using Constructors. Hope you enjoyed reading it…!!!
So let’s move to our second approach – Method dependency injection.