我有一个C#WebAPI应用程序,由TopShelf自托管。 我需要通过在应用程序启动时查询几个数据库来优化我的一些数据访问,然后缓存结果(这是静态的)以供我的WebAPI控制器进行任何后续访问。 我的解决方案包括两个项目:
ServiceHub.Topshelf.WebAPI(包含所有业务逻辑)和Topshelf.WebPI(仅托管WebApiConfigurator.cs)
进行此类数据缓存的正确方法是什么?
答案 0 :(得分:0)
正如Ric建议的那样,我已经看过Cache类了。以下是我在SIgnedContractsController.csc中完成缓存的内容:
using System.Runtime.Caching;
.....
ObjectCache cache;
List<Model.SignedContracts> allSignedContracts;
.....
cache = MemoryCache.Default;
allSignedContracts = cache["signed_contracts"] as List<Model.SignedContracts>;
if (allSignedContracts == null)
{
allSignedContracts = new List<Model.SignedContracts>();
CacheItemPolicy policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTimeOffset.Now.AddHours(1.0);
var result = (from contracts in new XPQuery<Model.SignedContracts>(uow) select contracts);
foreach (var item in result)
{
allSignedContracts.Add(item);
}
cache.Add("signed_contracts",allSignedContracts,policy);
}
然后,在GET方法中我做到了这一点:
public HttpResponseMessage Get()
{
var _americasPriorWeekThree = Convert.ToInt32((from contracts in allSignedContracts
where contracts.Region == "Americas"
select contracts.PriorWeek3).First());
.......