Junior — Middle
Millised meetodid tagavad sõltuvuste rakendamise koodis?
sobes.tech AI
Vastus AI-lt
Dependency Injection (DI) in C# is typically implemented in the following ways:
- Through the constructor — dependencies are passed to the class via constructor parameters. This is the most common and recommended method.
public class Service {
private readonly IRepository _repository;
public Service(IRepository repository) {
_repository = repository;
}
}
- Through properties (Property Injection) — dependencies are set via the class's properties.
public class Service {
public IRepository Repository { get; set; }
}
- Through methods (Method Injection) — dependencies are passed to methods that use them.
public class Service {
public void Execute(IRepository repository) {
// use of repository
}
}
To manage dependencies, DI containers (e.g., Microsoft.Extensions.DependencyInjection) are often used, which automatically create and provide the necessary objects.
This way, dependency injection makes the code more modular, testable, and maintainable.