在WebApi2项目中使用CacheOutput属性时,依赖项的解析失败

bol*_*sky 5 asp.net-web-api

在我的ASP.NET WebApi2项目中,我决定使用Strathweb.CacheOutput.WebApi2包来提供缓存和电子标签功能.但是,在放入CacheOutput属性后,我开始收到错误:

Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the dependency failed, type = "WebApi.OutputCache.Core.Cache.IApiOutputCache", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, WebApi.OutputCache.Core.Cache.IApiOutputCache, is an interface and cannot be constructed. Are you missing a type mapping?
Run Code Online (Sandbox Code Playgroud)

显然,包的内部DI容器无法解析缓存提供程序.

我使用属性的方式:

[HttpGet, Route("")]
[CacheOutput(ClientTimeSpan = 60 * 60 * 4, ServerTimeSpan = 60 * 60 * 4)]
public HttpResponseMessage Get(
    string products,
    int? startYear = null,
    int? endYear = null,
    int? drillDownYear = null,
    int? drilldownMonth = null,
     string callback = "")
    {
       ...
    }
Run Code Online (Sandbox Code Playgroud)

请注意,我也在我的应用程序中使用Unity作为DI容器.

Fil*_*p W 4

该库使用以下逻辑来查找缓存提供程序(使用第一个匹配项):

  1. 检查您Func<IApiOutputCache>PropertiesHttpConfiguration
  2. 签入已注册的IDependencyResolver
  3. 用途new MemoryCacheDefault()

当未找到注册时,通常IDependencyResolver会返回 null - 在这种情况下,您的 Unity 实现似乎会抛出 Ex。

您可以通过切换到更好的 DI 来缓解这种情况:) 或者只是在 Unity 容器中注册一个单例new MemoryCacheDefault()as 。IApiOutputCache

  • Filip W 在[后来的 github 问题](https://github.com/filipw/AspNetWebApi-OutputCache/issues/89) 上回答了这个问题。基本上,应用程序启动时需要这两行: `GlobalConfiguration.Configuration.CacheOutputConfiguration().RegisterCacheOutputProvider(() =&gt; new MemoryCacheDefault()); GlobalConfiguration.Configuration.CacheOutputConfiguration().RegisterDefaultCacheKeyGeneratorProvider(() =&gt; new DefaultCacheKeyGenerator());` (4认同)