Junior — Middle
Can you explain the concept of a DI container and its role in application development?
sobes.tech AI
Answer from AI
DI (Dependency Injection) container is a special component that manages the creation and binding of dependencies between objects in an application. Its main role is to automate the process of dependency injection to simplify testing, increase modularity, and reduce code coupling.
Instead of manually creating objects and passing dependencies to them, the DI container takes on this task: it stores information about which implementations to use for interfaces and creates objects with the required dependencies.
Example of usage in C# with a simple DI container:
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.");
}
}
// Registering and retrieving dependencies
var services = new ServiceCollection();
services.AddTransient<ILogger, ConsoleLogger>();
services.AddTransient<UserService>();
var provider = services.BuildServiceProvider();
var userService = provider.GetService<UserService>();
userService.CreateUser("Alice");
Here, the DI container creates UserService, automatically injecting the required ILogger implementation.