This is the final article in the series of articles, based on concept of dependency injection and how we can implement. This will be the concept of using Property 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
- Method dependency injection using using C# – Part 3
The use of this approach will be helpful in the case we would like to completely separate the method or constructor from receiving the dependency. It will be common to the entire class methods and not a single one. So you can use it in any of the methods of the class. We will be using the same example, which we used in our previous discussions. See the code below :
As the name suggests, this approach simply uses a property of the dependency, of an abstraction type. This property is used to access the methods defined in the concrete implementations of the dependency. Client code will simply assign the required dependency to the property and the methods of the dependent class will use this property, to use the underlined concrete implementation. So the code changes to:
We simply assign the XMLLogger type to the property declared in the User class. When _user calls its methods, the methods use the _iLogger property to call the LogInfo method. Depending on the concrete implementation of ILogger which _iLogger refers to, appropriate logger is called. Run the code and see the results below :
So this is how we implement the Property dependency injection. So with this article, our series of articles based on the concept of dependency injections also ends. Hope you enjoyed reading these articles…!!!