Junior — Middle
How can component dependency in code be reduced to improve its flexibility?
sobes.tech AI
Answer from AI
To reduce component dependencies in C# code and increase its flexibility, principles of dependency inversion and dependency injection are used. This allows separating object creation from their usage, making it easier to replace and test components.
Main approaches:
- Using interfaces or abstract classes to define contracts.
- Injecting dependencies through constructors, properties, or methods.
- Using dependency injection containers (DI containers), such as Microsoft.Extensions.DependencyInjection, Autofac, etc.
Example of dependency injection through 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 service = new UserService(logger);
service.CreateUser("Alice");
This approach reduces tight coupling of classes and facilitates maintenance and extension of the code.