Dependency Injection

Dependency injection (DI) is a design pattern in which an object receives its dependencies, rather than creating them itself. In C#, this can be achieved through constructor injection, property injection, or method injection. The dependencies are typically interfaces, allowing the client object to remain loosely coupled to the concrete implementations of these dependencies. DI promotes separation of concerns, making code more maintainable and testable.

The following steps for using dependency injection in your solution is listed below:

  1. Define an interface for the dependency (service) to be injected.
  2. Create a concrete class that implements the interface.
  3. Inject the dependency into the dependent class using a constructor, property, or method parameter.
  4. Use the dependency in the dependent class.

In the following code sample we use a Logger as an example to demonstrate dependency injection:

public class Logger
{
    public void Log(string message)
    {
        Console.WriteLine($"Log Message: {message}"); 
    }
}

Next, we define the Interface for the Logger, encapsulating the unnecessary details that we don’t need:

public interface ILogger
{
    void Log(string message);
}

Inject the dependency into a class:

public class UserService
{
    private readonly ILogger _logger;

    public UserService(ILogger logger)
    {
        _logger = logger;
    }

    // Use the dependency
    public void AddUser(string name)
    {
        // add user to database
        _logger.Log($"User {name} added.");
    }
}