Dependency injection in C# explained
Aug 26, 2023 pm 04:05 PMA dependency is an object that another object depends on. Dependency injection (or inversion) is basically providing an object with the objects it needs instead of letting it construct the object itself. This is a useful technique that makes testing easier because it allows you to mock dependencies.
For example, if class A calls a method on class B, and class B calls a method on class C, it means that A depends on B and B depends on C. Using dependency injection, we can pass an instance of class C to class B, and an instance of B to class A, instead of having these classes construct instances of B and C.
In the following example, Class Runner depends on class Logger. Note that an instance of Logger is created in the constructor of class Runner. There are some problems with this code.
This ties the logger class to the Runner, we cannot replace it with another class, No need to modify the Runner.
If Logger has any dependencies, then Worker must configure them first Instantiate the Logger.
Testing is more difficult. If Logger is a resource-intensive class, such as access network or file system, which can slow down the test. We can't replace it easily.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
Using dependency injection, we modify Runner's constructor to accept the interface ILogger instead of a concrete object. We change the Logger class to implement ILogger. This allows us to pass an instance of the Logger class to the Runner constructor. The advantage of this is that during testing we can create a TestLogger class that implements ILogger and pass it to the Runner's constructor.
Example
Real-time demonstration
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
Output
1 |
|
The above is the detailed content of Dependency injection in C# explained. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Method of copying code by C language compiler

What are the alternatives to NULL in C language

What are the web versions of C language compilers?

C language online programming website C language compiler official website summary

Is NULL still important in modern programming in C language?

C language compiler installation tutorial (computer version)
