Sobes.tech
Intern — Junior

What is the purpose of dependency injection in software modules?

sobes.tech AI

Answer from AI

Dependency Injection (DI) is used to increase the modularity and testability of software modules. Instead of creating dependencies inside a class, they are passed from outside, which makes it easy to replace implementations, simplifies maintenance, and extends the code.

For example, in C#, DI can be used to pass an implementation of an interface into a class constructor:

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.");
    }
}

This approach makes it easier to replace the logger with another (for example, a file logger) without changing the UserService class.

What is the purpose of dependency injection in… - sobes.tech