Sobes.tech
Junior — Middle

Can you explain the principle of dependency injection in programming code and its main purpose?

sobes.tech AI

Answer from AI

Dependency Injection (DI) is a pattern where an object receives its dependencies from outside rather than creating them itself. This increases modularity, testability, and flexibility of the code.

The main purposes of DI:

  • Separation of concerns: the class is not responsible for creating dependencies.
  • Simplification of testing: dependencies can be replaced with mocks or stubs.
  • Increased flexibility: easily change implementations of dependencies without modifying the class code.

Example in C# using constructor injection:

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; // dependency is injected from outside
    }

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

// When creating UserService, pass the required ILogger implementation
var service = new UserService(new ConsoleLogger());