Dependency injection using Constructor in C# – Part 2


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 :

Dependency injection and inversion of controls

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 :

Dependency injection using constructor

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 :

Dependency injection using constructor

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.

Advertisements

About Jasminder

.Net developer and blogger by profession, keen to learn new technologies, love nature, music and cricket.
This entry was posted in Design and Architecture and tagged . Bookmark the permalink.

I have a suggestion..

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s