Site icon

Introduction to Dependency Injection in C# with Examples

Dependency Injection (DI) is a design pattern to enhance the modularity and maintainability of software systems, it facilitates the management of dependencies between objects. In this blog we will deep dive into Dependency Injection and how you can implement it in C# with clear examples.

What is Dependency Injection?

The primary purpose of Dependency Injection is to decouple the object creation from the object (client) that uses them. It involves supplying an object (a client) with its dependencies (services or objects that it uses) externally instead of creating them directly inside the class.

Let’s take an example to understand how dependency helps modularity and easier testing.

Example for Dependency Injection Design Pattern:

Let’s take an example of designing a logging system that writes input string into a File, we want to make it more flexible so that it can be further extended to log input string in Database, Event or Console etc without making any further changes to the main logic.

Without using Dependency Injection in C#:

In the above example we haven’t used any dependency injection concept at all, when we run the above code then it generates below output.

No_Dependency_Injection_Output_1.0

Using Dependency Injection in C#:

Let’s rewrite above scenario using Dependency Injection concept.

When we run the above code then it generates below output.

Dependency_Injection_Output_2.0

Types of Dependency Injection

There are three ways of injecting dependencies:

Constructor Injection:

Constructor injection is where the required dependencies are injected through the constructor, In the above example constructor LoggingService(ILogging logging) is used to inject the dependencies. Let’s check below code snippet for same.

Example – 1:

Property Injection 

Property injection involves public properties used to inject dependencies.

Example – 2:

Method Injection:

Method injection is where the dependency is provided as a parameter to the method that requires it.

Example – 3:

Benefits of Dependency Injection?

Dependency Injection comes with several benefits:

Conclusion

Dependency Injection in C# provides a clean separation of concerns where components are easily manageable, testable, and maintainable. This helps to create more modular applications and reduce the dependencies among application components.

Thanks for checking this out 🙂 please visit some of the other blogs design pattern.

ASP.NET MVC Pattern as Web Development

MVC Design Pattern

 

Exit mobile version