Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Dependency Injection Pattern (Loose Coupling)

2.82/5 (6 votes)
1 May 2008CPOL2 min read 1   415  
Description of Dependency Injection Pattern

Problem (Object Dependency)

We have object dependency when an object ‘x’ uses an object ‘y’, we say that ‘x’ is dependent on ‘y’. Object dependency becomes a problem when object ‘x’ needs to use another object dynamically, object ‘z’, instead of ‘y’. Strong dependency mixes both object (Data) and relation (logic) in one place and result in tight coupling that render the code much harder to modify and adjust.

Solution (Loose Coupling)

Genuine solution is to implement loose coupling pattern, such as dependency injection. Indeed, dependency injection allows objects to relate to each other but through an interface so that object ‘x’ will use interface ‘i’ while both ‘y’ & ‘z’ implement the interface ‘i’. This methodology allows the isolation between the implementation, creation, and logical dependency of an object.

Pros & Cons

Pros

  1. Loose coupling
  2. Centralized configuration

Cons

  1. Adding additional coding to handle relations
  2. Linking objects together will become an overhead by itself when having too many instances

Example

Farm investor winform advisor suggests the amount of money required to have successful farm investment according to the number and type of animals raised in the farm. I did it for my grand ma “Rquia” because she has a small farm and likes cows and sheep very much. Grand hug to her!

Example.JPG

Implementation

The code includes three examples of implementing dependency injection using:

1) Constructor

Using constructor is a good method. It does all in the creation of the object but once the dependency is set, there is no way to change it. More flexible method would be using setter.

DIConstructor.JPG

2) Setter

Setter is very flexible in setting the dependency dynamically, but for further loosening. It is better to make the relation completely handled by interfaces. So that, it is not ‘x’ that is dependent on ‘i’ but it is ‘ix’ the interface implemented by ‘x’ that depends on ‘i’ hence we can change the dependency from both ends. It is no more class dependent on an interface but an interface dependent on an interface. This ‘high loosely coupling’ is feasible through interface dependency injection.

sertterConstructor.JPG

3) Interface

In this case, an interface is dependent on another interface which lets the objects independent from any logical relation between each other.

DIInterface.JPG

History

  • 1st May, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)