Junior — Middle
Explain the principle of dependency injection in programming code and its advantages.
sobes.tech AI
Answer from AI
Dependency Injection (DI) is a design pattern where an object receives its dependencies from outside rather than creating them itself. This enhances modularity and testability of the code.
Advantages of DI:
- Easier testing — dependencies can be easily replaced with mocks or stubs.
- Loose coupling — classes do not depend on specific implementations, only on abstractions.
- Increased flexibility — it's easy to change dependency implementations without modifying the code that uses them.
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) // dependency injected via constructor
{
_logger = logger;
}
public void CreateUser(string name)
{
// user creation logic
_logger.Log($"User {name} created.");
}
}
// Usage:
var logger = new ConsoleLogger();
var service = new UserService(logger);
service.CreateUser("Alice");