依赖注入(Dependency Injection, DI)是一种设计模式,用于解耦组件之间的依赖关系,提高代码的可测试性和可维护性。以下从零开始逐步介绍依赖注入的基本原理,以及如何使用流行的DI容器(如Autofac、Unity)进行配置,包含详细的代码和注释。
一、依赖注入原理
1. 依赖关系
Csharp
public class OrderService
{
private readonly ILogger _logger;
private readonly IOrderRepository _repository;
public OrderService(ILogger logger, IOrderRepository repository)
{
_logger = logger;
_repository = repository;
}
// ...
}
public interface ILogger { /* ... */ }
public interface IOrderRepository { /* ... */ }
在上面的例子中,OrderService
依赖于ILogger
和IOrderRepository
。通过构造函数注入这些依赖,使得OrderService
无需关心依赖的具体实现。
2. 依赖注入容器<