首页 > 解决方案 > 通过 .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

如何用修饰的实现覆盖范围服务?

标签: c#asp.net-core.net-coreazure-functions

解决方案


要使用修饰的缓存服务来修饰服务,您可以使用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


推荐阅读