January 29, 2023

Dependency Injection in C#

Dependency Injection (DI) is a programming technique that makes a class independent from its dependencies. This article describes a quick overview of dependency injection: what is it, and when to use it. Summer of the article:

  1. What is Dependency Injection?
  2. Why we need Dependency Injection?
  3. Dependency Injection Framework

What is Dependency Injection?

Dependency or dependent means relying on something for work. For example, we can say, our daily life is relying too much on smartphones. That means we are dependent on smartphones.

In a programming language, when class A uses some functionality of class B, then we can say class A has a dependency of class B. In C# language, if we want to use a method of other classes, at first we need to create the object of that class. For the above example, class A needs to create an instance of class B.

In short we can say, transferring the task of creating the object to someone else and directly using the dependency is call dependency injection or DI. DI is one of the possible implementations of the Dependency Inversion Principle (DIP), which is the fifth principal of SOLID.

Types of DI

  • Constructor injection
  • Property injection
  • Method injection

Benefits of DI

  • It helps to enable loose coupling, which is very important in software programming.
  • It is complex to learn. And overused can lead to management issues and other problems.

Disadvantages of DI

  • Some compile time errors may occurred in run-time.
  • It helps in unit testing.

Dependency Injection Framework

We can implement DI in our own style or can use third party libraries or frameworks. Some libraries or frameworks that implement DI is given bellow:

  • Sprint (Java)
  • Castle Windsor (.Net)
  • Google Guice (java)
  • Lamar
  • LightInject
  • Ninject
  • SimpleInjector
  • Spring.Net
  • Unity (.Net)
  • LinFu
  • Managed Extensibility Framework (MEF)
  • PicoContainer.Net
  • Simple Injector
  • Structure Map
  • Microsoft.Extensions.DependencyInjection (.Net)

Rashedul Alam

I am a software engineer/architect, technology enthusiast, technology coach, blogger, travel photographer. I like to share my knowledge and technical stuff with others.

View all posts by Rashedul Alam →

One thought on “Dependency Injection in C#

Leave a Reply

Your email address will not be published.