Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolution of the dependency failed when using CacheOutput attribute in WebApi2 project

In my ASP.NET WebApi2 project I decided to use the Strathweb.CacheOutput.WebApi2 package to provide caching and e-tag functionality. However, after putting the CacheOutput attribute I started to get an error:

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?

Obviously, the package's internal DI container cannot resolve a cache provider.

The way I use the attribute:

[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 = "")
    {
       ...
    }

Just to note, I am also using Unity in my application as a DI container.

like image 597
bolkhovsky Avatar asked Sep 30 '22 18:09

bolkhovsky


1 Answers

The lib uses the following logic to find cache provider (the first match is used):

  1. Checks for a Func<IApiOutputCache> in the Properties of your HttpConfiguration
  2. Check in the registered IDependencyResolver
  3. uses new MemoryCacheDefault()

Typically IDependencyResolver will return null when registration is not found - i nthis case looks like your Unity implementation is throwing an Ex instead.

You can mitigate that by switching to a better DI :) or just register a singleton of new MemoryCacheDefault() as IApiOutputCache in your Unity container.

like image 182
Filip W Avatar answered Oct 04 '22 20:10

Filip W