Dependency Injection using Property in C# – Part 4


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.

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 :

Dependency injection and inversion of controls

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:

Property dependency injection

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 :

Property dependency injection

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…!!!

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