Sobes.tech
Junior — Middle

Explain the principle of Inversion of Control and how it is related to dependency injection in applications.

sobes.tech AI

Answer from AI

Inversion of Control (IoC) is a principle where the management of creating and binding dependencies of objects is delegated to an external container or framework, rather than being implemented within the objects themselves.

Dependency Injection (DI) is a specific implementation of IoC, where the dependencies of an object are provided to it from outside (for example, through a constructor, setter, or interface).

This allows:

  • Simplifying testing (easily substituting mocks or stubs).
  • Increasing modularity and reusability of code.
  • Reducing coupling between components.

Example in C# with 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;

    // Dependency is injected from outside
    public UserService(ILogger logger) {
        _logger = logger;
    }

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

// In main code
ILogger logger = new ConsoleLogger();
UserService service = new UserService(logger);
service.CreateUser("Alice");

Here, UserService does not create ConsoleLogger itself but receives it from outside, which aligns with the IoC principle.