Sobes.tech
Junior — Middle

Can you explain the concept of Dependency Injection and its application in development?

sobes.tech AI

Answer from AI

Dependency Injection (DI) is a design pattern that allows dependencies of an object to be passed from outside rather than created inside the object itself. This increases modularity, testability, and simplifies dependency management.

In C#, DI is often implemented through constructors, properties, or methods. For example, if a class depends on a service interface, this service is passed into the 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.");
    }
}

// Usage
var logger = new ConsoleLogger();
var userService = new UserService(logger);
userService.CreateUser("Ivan");

In real applications, dependency injection containers (e.g., Microsoft.Extensions.DependencyInjection) are often used to automatically create and manage the lifecycle of objects.