How to use LazyCache with async function that takes parameter

2k Views Asked by At

I am trying to use LazyCache. The api has GetOrAddAsync that takes Func<Task<T>>. This is the function that build stuff i want to cache.
However the function that i have takes input parameter. The signature of my function is Func<int,Task<T>>

So as expected i am getting compilation error

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

How do i pass input parameter to my function?

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

There are 1 best solutions below

0
On

It works for me with some small changes:

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));
    }
}