Dependency Injection in C# with example for beginners

Dependency injection is a programming paradigm that makes a class independent of its dependencies or, in other words, loosely coupled. This allows you to replace dependencies without having to change the class that relies on them. It also lowers the risk of changing a class just because one of its dependencies changed.

Dependency Injection is discussed in a famous blog post by Martin Fowler

Inversion of Control Containers and the Dependency Injection pattern

Fowler’s Example
)

The code above has two concrete dependencies.
-A reference to a concrete class that implements MovieFinder

  • A reference to a hard-coded string

The name of the movie database cannot change without causing MovieLister to be changed and recompiled

Our Goal

Our goal is to remove as much as possible the new keyword from MovieLister class
As much as possible, get rid of code with the form

this.finder=new XmlMovieFinder(“movies.xml”);

Types of dependency injection

There are several types of dependency injection like

  • Constructor Injection
  • Property Injection
  • Method Injection
  • Interface injection comparison.

Let’s understand the first two with some real-world example.

Constructor Injection

You can in the above code that we are passing IMovieFinder in the constructor of the MovieLister instead of creating a new instance in the constructor.

Property Injection(## aka setter injection)

The injector supplies dependency through the use of the public property of a client class during property injection (also known as the Setter Injection).

So, what is dependency injection?

The idea is that classes in an application express their dependencies in very indirect ways. MovieLister needs MovieFinder and Main needs a MovieListerTo achieve this, we need a third party system known as an Inversion of Control container or a dependency injection framework, which then injects (or inserts) a class that will meet that dependency at run-time.

The intent behind dependency injection is to achieve separation of concerns of construction and use of objects. This can increase readability and code reuse.

You May Like

إرسال تعليق

Please do not post any spam link in the comment box😊

أحدث أقدم

Blog ads

CodeGuru