Sobes.tech
Junior — Middle

What is the main task of Dependency Injection in applications?

sobes.tech AI

Answer from AI

Dependency Injection (DI) is a design pattern that allows dependencies (such as services, repositories) to be injected into a class from outside, rather than created within the class.

The main goal of DI is to increase the modularity, testability, and flexibility of an application, making it easy to replace dependency implementations without changing the class code.

In C#, this is often implemented through constructors or properties:

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

public class ConsoleLogger : ILogger {
    public void Log(string message) => Console.WriteLine(message);
}

public class UserService {
    private readonly ILogger _logger;

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

    public void CreateUser(string name) {
        // user creation logic
        _logger.Log($"User {name} created");
    }
}

Here, UserService does not create ILogger itself but receives it from outside, which simplifies replacing the logger, for example, with a test logger.

DI promotes loose coupling of components and makes code maintenance easier.