由于ASP.NET Core提供了可以注入(inject)的MemoryCache,而且是单例,那么应该注入(inject)到Controller中还是Service中呢?
我有一个 Controller ,它调用服务来从数据库或外部服务获取信息。在 Controller 中,我只会转换其中一些信息(将对象列表转换为 List<SelectListItem>
)。
我应该在服务级别缓存并将缓存的信息返回给 Controller 还是应该缓存已经转换的信息(List<SelectListItem>
甚至服务原始信息)?
最佳答案
该服务负责更昂贵的操作(从数据库等获取数据)。相比之下,您在 Controller 中执行的转换对性能的影响可以忽略不计,因此从性能角度来看,将此职责放入 Controller 中不会有任何帮助。
此外,同一个服务方法可能会从多个位置调用,在这种情况下,您可以从服务层中的缓存中获得更多好处。
从“关注点分离”的角度来看,您可以使用的另一种策略(我已成功使用该策略)是将缓存责任移至其自己的类中。
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),每当有人请求存储库时,将真实存储库注入(inject)到缓存中:
Bind<IThingRepository>().ToMethod(c => new ThingRepositoryCache(
c.Get<ThingRepository>(),
cache));
关于c# - MVC 6的MemoryCache应该在 Controller 级别使用还是在服务级别使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37729234/