如何将LazyCache与带有参数的异步功能一起使用

时间:2020-01-17 22:45:22

标签: asp.net-core .net-core coreclr memorycache lazycache

我正在尝试使用LazyCache。该API的GetOrAddAsync占用Func<Task<T>>。这是构建我要缓存的内容的功能。
但是我有的功能需要输入参数。我函数的签名是Func<int,Task<T>>

所以按预期,我会收到编译错误

cannot convert from 'System.Func<int, System.Threading.Tasks.Task<string>>' to 'System.Func<Microsoft.Extensions.Caching.Memory.ICacheEntry, System.Threading.Tasks.Task<string>>'

如何将输入参数传递给函数?

public class MyCacheService
{
    private readonly IAppCache _cache = null;        

    public MyCacheService(IAppCache cache)
    {
        _cache = cache;
    }

    public async Task<string> Find(int key, Func<int, Task<string>> func)
    {
        //?? compilation error here
        // i want to pass key to function as input parameter
        return await _cache.GetOrAddAsync<string>(key.ToString(), func);
    }
}


public class DatabaseService
{
    public async Task<string> GetStringFromDataBase(int id)
    {
        await Task.FromResult(0);
        return "Some string from database based on input parameter id";
    }
}

public class Worker
{
    private readonly MyCacheService _cacheService;
    private readonly DatabaseService _databaseService;

    public Worker(MyCacheService cacheService, DatabaseService databaseService)
    {
        _cacheService = cacheService;
        _databaseService= databaseService;
    }

    public async Task DoWork()
    {
        await _cacheService.Find(1234, _databaseService.GetStringFromDataBase);
    }
}

DOTNETFIDDLE

1 个答案:

答案 0 :(得分:0)

它对我有用,但有一些小的变化:

public class MyCacheService
{
    private readonly IAppCache _cache = null;

    public MyCacheService(IAppCache cache)
    {
        _cache = cache;
    }

    public async Task<string> Find(int key, Func<ICacheEntry, Task<string>> func)
    {
        return await _cache.GetOrAddAsync<string>(key.ToString(), func);
    }
}

public class DatabaseService
{
    public async Task<string> GetStringFromDataBase(ICacheEntry entity)
    {            
        await Task.FromResult(int.Parse(entity.Key.ToString()));
        return "Some string from database based on input parameter id";
    }
}

public class Worker
{
    private readonly MyCacheService _cacheService;
    private readonly DatabaseService _databaseService;

    public Worker(MyCacheService cacheService, DatabaseService databaseService)
    {
        _cacheService = cacheService;
        _databaseService = databaseService;
    }

    public async Task DoWork()
    {
        await _cacheService.Find(1234, (ICacheEntry x) => _databaseService.GetStringFromDataBase(x));
    }
}