我没有在每次加载 cshtml 时都查询数据库,而是将模板放在 Session 变量中,并在 Layout.cshtml 中根据模板呈现不同的 css
如果访问数据库是您唯一关心的问题,并且您已经抽象了存储库(或用户存储,如果您将其存储在身份类型上),则可以使用装饰器模式来实现本地缓存。
public interface IUserRepository
{
string GetUserTheme(int userId);
void SetUserTheme(int userId, string theme);
}
public class CachedUserRepository : IUserRepository
{
private readonly IMemoryCache cache;
private readonly IUserRepository userRepository;
// Cache Expire duration
private static TimeSpan CacheDuration = TimeSpan.FromMinutes(5);
public CachedUserRepository(IUserRepository userRepository, IMemoryCache memoryCache)
{
if (userRepository == null)
throw new ArgumentNullException(nameof(userRepository));
if (memoryCache == null)
throw new ArgumentNullException(nameof(memoryCache));
this.userRepository = userRepository;
this.cache = memoryCache;
}
public string GetUserTheme(int userId)
{
string theme;
// adding a prefix to make the key unique
if (cache.TryGetValue($"usertheme-{userId}", out theme))
{
// found in cache
return theme;
};
// fetch from database
theme = userRepository.GetUserTheme(userId);
// put it into the cache, expires in 5 minutes
cache.Set($"usertheme-{userId}", theme, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = CacheDuration });
return theme;
}
public void SetUserTheme(int userId, string theme)
{
// persist it
userRepository.SetUserTheme(userId, theme);
// put it into the cache, expires in 5 minutes
cache.Set($"usertheme-{userId}", theme, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = CacheDuration });
}
}
问题是,默认 ASP.NET Core DI 系统中没有对装饰器的内置支持。您必须使用第 3 方 IoC 容器(Autofac、StructureMap 等)。
你当然可以这样注册
services.AddScoped<IUserRepository>(container => {
return new CachedUserRepository(container.GetService<UserRepository>(), container.GetServices<IMemoryCache>());
});
但这有点麻烦。否则将其存储在一个长期存在的 cookie 中,它的优点是当用户未登录时主题仍然处于活动状态,并且您可以在用户登录时设置 cookie。