Dependency Injection (DI) is a software design pattern. Dependency Injection reduces the hard-coded dependencies among your classes by injecting those dependencies at run time instead of design time technically.
Dependency Injection reduces the hard-coded dependencies among your classes by injecting those dependencies at run time instead of design time technically.
It is critical to take a step back to the basics of designing an object-oriented application where a major facet of design is “loose coupling.” This means that objects only have as many dependencies as needed to do their jobs–and, the number of dependencies should be limited.
This article explains how to implement Dependency Injection in C# and .NET code.
We have the following ways to implement Dependency Injection.
1. Constructor Injection
2. Setter Injection
3. Method Injection
Since DI is utilized to make code maintainable, it uses a pattern with a builder object to initialize objects and give the required dependencies to the object. As you can see, you can now “inject” a dependency from outside the class.
How Dependency Injection C# Works
Ø High-level modules should not depend on low-level modules. Both should depend on abstractions.
Ø Abstractions should not depend upon details. Details should depend upon abstractions.
Constructor Injection in C#:
1. This is a widely used way to implement DI.
4. Recommended to use when the injected dependency, you are using across the class methods.
5. It addresses the most common scenario where a class requires one or more dependencies.
We can use the injection component anywhere within the class. It addresses the most common scenario where a class requires one or more dependencies. The following is an example:
By passing the services that implemented the text interface the builder assembled the dependencies.
We use constructor injection, but there are some cases where I need a parameter-less constructor, so we need to use property injection. The following is an example:
You cannot control when the dependency is set at all, it can be changed at any point in the object's lifetime.
Method Injection in C#:
1. Inject the dependency into a single method and generally for the use of that method.
The following is an example:
Advantages of Dependency Injection
This article helps to reduces class coupling, increase code reuse, improve code maintainability, improve application testing and help to easily do unit testing. In this article with code samples, we saw some use cases of dependency injection using C# and .NET.