What is dependency injection?
For a while, .NET has natively supported the dependency injection (often referred to as DI) software design pattern.
Dependency injection is a way to implement in .NET the Inversion of Control (IoC) pattern between service classes and their dependencies. By the way, in .NET, many fundamental services are built with dependency injection, such as logging, configuration, and other services.
Let’s look at a practical example to get a good understanding of how it works.
Generally speaking, a dependency is an object that depends on another object. In the following example, we have a LogWriter
class with only one method inside, called Log
:
public class LogWriter { public void Log(string message) { Console.WriteLine($"LogWriter.Write (message: \"{message}\")"); ...