Method dependency injection using C# – Part 3

Continuing with the series of articles, based on concept of dependency injection, next in our discussion will be the concept of using Method injection, to inject the dependency to a dependent component. If you would like to start from the basic, then i would recommend you to read the following articles first.

We already have the concept of Constructor injection. But this will have the limitation that the dependent class will have the same reference of dependency, during its life time. We may have different methods in a class, where we may need one kind of dependency and in the second method, we may need another kind of dependency. Or we may be requiring the dependent component only for single method of class. Then using the constructor injection is nothing more redundant code. For such a situation, we have the concept of dependency injection, using Methods.

To continue further, we will have the same code, where we have one common interface ILogger, having a method named LogInfo. Two classes, TextLogger and XMLLogger will implement this interface method and will have their own code of logging the info. In our example, we will simply print the info received. See the code below :Dependency injection and inversion of controls

Next, we have a class User, which will be having two methods, one is SaveData and other is DeleteData. SaveData will log information using TextLogger and DeleteData will log information using XMLLogger. So here, we need two different logger types. Constructor injection would not have worked in this case, or we might have passed multiple logger types in constructor(which is not a good design approach). So we pass the required logger dependency, as an interface instance, during the actual method call. Finally client code calls the User class methods. See the code below :

Dependency injection using Methods

Run the code. When the User class methods are called, depending on the logger type received, appropriate logging method is called. For SaveData, TextLogger is used and for DeleteData, XMLLogger is used. See the results below.

Dependency injection using Methods

Easy to implement, wasn’t it. So this is how we implement the dependency injection using Methods. Let’s move to our third and final approach – Property based dependency injection.


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: Logo

You are commenting using your 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