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.
- Dependency injection and inversion of control – Part 1
- Constructor dependency injection using C# – Part 2
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 :
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 :
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.
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.