Junior — Middle
What methods ensure dependency injection in the code?
sobes.tech AI
Answer from AI
Dependency Injection (DI) in C# is usually implemented in the following ways:
- Through 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 through the class 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 repository
}
}
For dependency management, DI containers (e.g., Microsoft.Extensions.DependencyInjection) are often used, which automatically create and provide the necessary objects.
Thus, dependency injection allows the code to be more modular, testable, and maintainable.