## .NET7依赖注入 装饰器模式
装饰器(Decorator)模式是一种在不改变原始类的情况下增强其功能的模式。在 DI 中,装饰器模式常用于在不改变原始服务的实现的情况下增强其功能,例如在日志服务中增加性能统计和异常记录。通过创建装饰器类,用户可以在不改变原始服务实现的情况下增加新的功能。示例代码如下:
```csharp
// 原始服务
public interface IMyService
{
void DoSomething();
}
public class MyService : IMyService
{
public void DoSomething()
{
// ...
}
}
// 日志装饰器
public class LoggingMyService : IMyService
{
private readonly ILogger _logger;
private readonly IMyService _myService;
public LoggingMyService(ILogger<LoggingMyService> logger, IMyService myService)
{
_logger = logger;
_myService = myService;
}
public void DoSomething()
{
_logger.LogInformation("DoSomething method called");
_myService.DoSomething();
}
}
services.AddScoped<IMyService, MyService>();
services.AddScoped<IMyService>(serviceProvider =>
{
var originalService = serviceProvider.GetRequiredService<IMyService>();
return new LoggingMyService(
serviceProvider.GetRequiredService<ILogger<LoggingMyService>>(),
originalService);
});
```