如何在单例服务中使用瞬态服务?

How can I use a transient service within a singleton service?

我有一些数据想保留在内存中,因为它不会经常更改,所以我打算使用单例服务

然而,当数据发生变化时,我需要从数据库中获取它,这需要一个瞬态服务

我该怎么做,因为无法将瞬态服务注入到单例服务中?

保罗

您需要创建另一个临时服务来使用您的数据库并更新您的缓存。我们称它为 dataProviderService。然后注入临时数据库服务和单例缓存服务。像这样

public class DataProviderService : IDataProviderService
{
    private readonly ICacheStorage cache;
    private readonly DbContext dbContext;

    public DataProviderService(ICacheSotrage cache, DbContext dbContext)
    {
        this.cache = cache;
        this.dbContext = dbContext;
    }

    public async Task<Something> GetSomething(CancellationToken cancellationToken)
    {
        if (data exist in cache and not expired)
            return cache.GetSomething();

        var items = await dbContext.GetSomething(cancellationToken);
        cache.SetSomething(items);

        return items;
    }
}

services.AddTransient<IDataProviderService, DataProviderService>();

切勿将瞬态服务注入单例服务。它只会让你的代码不可靠。