将 Generic.List 转换为 System.Threading.Task.Generic.List 时出现问题

2024-02-19

我正在尝试创建模拟IMemoryCache.TryGetValue方法,但当它命中时它会返回以下错误cache.Get(cacheKey):

无法转换类型的对象'System.Collections.Generic.List`1[ConnectionsModel]' to type 'System.Threading.Tasks.Task`1[System.Collections.Generic.List`1[ConnectionsModel]

这是模拟:

 private static Mock<IMemoryCache> ConfigureMockCacheWithDataInCache(List<ConnectionsModel> auth0ConnectionsResponse)
 {
        object value = auth0ConnectionsResponse;
        var mockCache = new Mock<IMemoryCache>();
        mockCache
            .Setup(x => x.TryGetValue(
                It.IsAny<object>(), out value
            ))
            .Returns(true);
        return mockCache;
    }

下面是测试方法:

var connectionList = new List<ConnectionsModel>();
var connectionsModel= new ConnectionsModel()
{
     id = "1",
    name = "abc",
    enabled_cons = new List<string>() { "test" }
};
connectionList.Add(connectionsModel);
var mockObject = ConfigureMockCacheWithDataInCache(connectionList);
var sut = new MyService(mockCache.Object);
// Act
var result = await sut.GetConnection(_clientId);

这是它命中的服务:

public async Task<ConnectionsModel> GetConnection(string clientId)
{
    var connections = await _cacheService.GetOrSet("cacheKey", ()=> CallBack());
    var connection = connections.FirstOrDefault();
    return connection;
}
private async Task<List<ConnectionsModel>> CallBack()
{
    string url = url;
    _httpClient.BaseAddress = new Uri(BaseUrl);
    var response = await _httpClient.GetAsync(url);
    response.EnsureSuccessStatusCode();
    return await response.Content.ReadAsAsync<List<ConnectionsModel>>();
}

以及缓存扩展方法:

   public static T GetOrSet<T>(this IMemoryCache cache, string cacheKey, Func<T> getItemCallback, double cacheTimeout = 86000) where T : class
    {
        T item = cache.Get<T>(cacheKey);
        if (item == null)
        {
            item = getItemCallback();
            cache.Set(cacheKey, item, DateTime.Now.AddSeconds(cacheTimeout));
        }
        return item;
    }

这条线之后T item = cache.Get<T>(cacheKey);我收到上述异常。我怎样才能解决这个问题?


考虑创建额外的扩展重载以允许使用异步 API

public static async Task<T> GetOrSet<T>(this IMemoryCache cache, string cacheKey, Func<Task<T>> getItemCallback, double cacheTimeout = 86000) where T : class
{
    T item = cache.Get<T>(cacheKey);
    if (item == null)
    {
        item = await getItemCallback();
        cache.Set(cacheKey, item, DateTime.Now.AddSeconds(cacheTimeout));
    }
    return item;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 Generic.List 转换为 System.Threading.Task.Generic.List 时出现问题 的相关文章

随机推荐