c# - 通过 .Net Core 2.2、Azure Functions 对具有多种实现的装饰器模式进行依赖注入
问题描述
我需要注入依赖Startup.cs
public class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddTransient<IAppService, AppService>();
//how to inject for the rest
}
}
实现以下行:
new AppService(new CacheRepository(new ConfigRepository()))
而不是下面或其他
new AppService(new ConfigRepository())
具有以下多种实现的装饰器模式:
public class ConfigRepository : IRepository
{
public async Task<IEnumerable<Data>> ReadDataAsync()
{
//...
}
}
public class CacheRepository : IRepository
{
private readonly IRepository _pository;
public CacheConfigRepository(IRepository repository)
{
_pository = repository;
}
public async Task<IEnumerable<Data>> ReadDataAsync()
{
//...
}
}
环境:.Net Core 2.2、Azure Functions
更新
回答:
感谢@Timo 提供以下链接 https://github.com/khillang/Scrutor
解决方案
要使用修饰的缓存服务来修饰服务,您可以使用Scuter。
例子:
public class MyService : IMyService
{
private readonly IRepository _repository;
public MyService(IRepository repository)
{
_repository = repository;
}
public async Task<IEnumerable<Data>> ReadDataAsync()
{
//...
}
}
修饰的缓存服务:
public class MyCacheService : IMyService
{
private readonly IMyService _myService;
private readonly ICacheRepository _cacheRepository;
public MyCacheService(IMyService myService, ICacheRepository cacheRepository)
{
_myService = myService;
_cacheRepository = cacheRepository;
}
public async Task<IEnumerable<Data>> ReadDataAsync()
{
var cachedKey = "SomeKey";
(isCached,value) = await _cacheRepository.ReadDataAsync();
if (isCached)
retrun value;
var result = await _myService.ReadDataAsync();
return result;
}
}
启动.cs:
services.AddSingelton<IMyService, MyService>();
services.Decorate<IMyService, MyCacheService>();
请注意,在此示例中,我添加了一个不同的界面ICacheRepository
。
推荐阅读
- java - 如何使用 InvocationHandler#invoke(...) 方法的 `proxy` 参数?
- php - 将标头的值回显给客户端
- python - 如何将 pywaffle 图表作为 matplotlib 子图的一部分包含在内?
- laravel - Laravel Yajra 不接受 post/get 查询请求
- reactjs - 如何从道具设置 ANT DESIGN INITIAL VALUE 形式
- mysql - 来自 docker-compose 的 mysql 副本是否已复制?
- python - 创建带有标题的多个直方图的子图
- android - Android MediaRecorder 保存文件路径
- optimization - socket.io 在使用路径时是否重用连接?
- javascript - 如何在 HTML 中隐藏链接的 JavaScript 文件