Junior — Middle
What is dependency injection and what are its advantages and disadvantages when used in a project?
sobes.tech AI
Answer from AI
Dependency Injection (DI) is a design pattern where objects receive their dependencies from outside rather than creating them themselves. In C#, this is often implemented through constructors, properties, or methods.
Advantages:
- Improves testability of the code, as dependencies can be easily replaced with mocks.
- Enhances modularity and flexibility, making it easier to replace components.
- Reduces coupling between classes.
Disadvantages:
- Complicates the project structure, especially when used improperly.
- Requires additional time for setup and understanding.
- May lead to excessive abstraction if used unnecessarily.
Example of 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;
}
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");