MVC 6的MemoryCache应该用在Controller级别还是Service级别?

MVC 6's MemoryCache should be used at a Controller level or at a Service level?

由于ASP.NETCore提供了一个可以注入的MemoryCache,并且是单例的,应该注入到Controller中还是注入到Service中?

我有一个控制器调用服务从数据库或外部服务中获取信息。在控制器中,我只会转换部分信息(将对象列表转换为 List<SelectListItem>)。

我应该在服务级别缓存并将缓存的信息 return 缓存到控制器还是应该缓存已经转换的信息(List<SelectListItem> 甚至服务原始信息)?

与其说是服务问题,不如说是控制器问题。

该服务负责更昂贵的操作(从数据库或类似数据库中获取数据)。与此相比,您在控制器中执行的转换对性能的影响可以忽略不计,因此从性能的角度来看,将此职责放入控制器中无济于事。

此外,同一个服务方法可能会被多个地方调用,在这种情况下,您会从服务层的缓存中获得更多好处。

从 "separation of concerns" 的角度来看,您可以使用的另一种策略是将缓存责任转移到它自己的 class。

public interface IThingRepository
{
  IReadOnlyCollection<Thing> GetThings();
}
public class ThingRepository : IThingRepository
{
  //...
}
public class ThingRepositoryCache : IThingRepository
{
  IThingRepository realRepository;
  MemoryCache cache;

  public ThingRepositoryCache(IThingRepository realRepository,
    MemoryCache cache)
  {
    this.realRepository = realRepository;
    this.cache = cache;
  }

  public IReadOnlyCollection<Thing> GetThings()
  {
    return cache["things"] ?? cache["things"] = this.realRepository.GetThings();
  }
}

使用类似这样的 DI 绑定,在有人请求存储库时将真实存储库注入缓存:

Bind<IThingRepository>().ToMethod(c => new ThingRepositoryCache(
   c.Get<ThingRepository>(),
   cache));