首页 > 解决方案 > 无法将 LazyCache 与 Suave 的 WebPart 一起使用

问题描述

我正在尝试使用 LazyCache ( https://github.com/alastairtree/LazyCache ) 来缓存一些 API 请求。

代码如下:

let private cache = CachingService()
let doAPIStuff some parameters : WebPart = ...

let result = cache.GetOrAdd(hashedRequest, (fun _ -> doAPIStuff))

但我得到这个编译错误:

  WebAPI.fs(59, 17): [FS0041] No overloads match for method 'GetOrAdd'.
Known types of arguments: string * ('a -> WebPart)
Available overloads:
 - (extension) IAppCache.GetOrAdd<'T>(key: string, addItemFactory: Func<'T>) : 'T // Argument 'addItemFactory' doesn't match
 - CachingService.GetOrAdd<'T>(key: string, addItemFactory: Func<Extensions.Caching.Memory.ICacheEntry,'T>) : 'T // Argument 'addItemFactory' doesn't match

这些是可用的类型:

在此处输入图像描述

所以我可以这样做:

let doAPIStuff some parameters : Object = ...

并将我的 WebPart 装箱,它工作正常。我知道 WebPart 是一个函数(在另一个问题中感谢 Fyodor),但我不明白为什么函数本身不能作为对象在缓存中。

标签: cachingf#suave

解决方案


我认为在这种情况下您需要显式创建Func委托,否则 F# 编译器无法区分这两个重载。

第二个参数的类型(在基本情况下)是Func<'T>一个函数,获取unit并返回要缓存的值。这也意味着,在这个函数内部,您应该doAPIStuff使用参数作为参数进行调用。

假设这是在一些接受 , 的actualRequest处理程序中someparameters以下应该可以工作:

let cache = CachingService()

let doAPIStuff some parameters : WebPart = 
  failwith "!"

let actualRequest some parameters = 
  let hashedRequest = some + parameters
  let result = 
    cache.GetOrAdd(hashedRequest, 
      Func<_>(fun () -> doAPIStuff some parameters))
  result

推荐阅读