1. 首先使用Configuration Console, 在blocks里面 Add Caching Setteings. 设置一些参数,比如Expiration Polling Frequency(seconds), 这个是指每隔指定的时间,cache block会检查那些过期的cache item,并且把他们删除掉。
2. 配置好以后可以保存为一个config文件,然后把config内容拷贝到你的project中的配置文件中。
<configSections>
<section name="cachingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<cachingConfiguration defaultCacheManager="Data Cache Manager">
<cacheManagers>
<add name="Data Cache Manager" type="Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
expirationPollFrequencyInSeconds="3600" maximumElementsInCacheBeforeScavenging="1000"
numberToRemoveWhenScavenging="10" backingStoreName="NullBackingStore" />
</cacheManagers>
<backingStores>
<add type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="NullBackingStore" />
</backingStores>
</cachingConfiguration>
3. 在你的project中引入一些dll。
Microsoft.Practices.EnterpriseLibrary.Caching.dll
Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography.dll
Microsoft.Practices.EnterpriseLibrary.Caching.Database.dll
Microsoft.Practices.EnterpriseLibrary.Data.dll
Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.dll
4. 现在就可以使用cache了,下面的是一个简单的使用cache功能的方法。
private Instance GetInstanceCache(string guid)
{
Instance ins = null;
string key = "INS" + guid;
ICacheManager defaultCache = EnterpriseLibraryContainer.Current.GetInstance<ICacheManager>();
if (defaultCache.Contains(key))
{
object cache = defaultCache.GetData(key);
if (cache != null)
{
ins = cache as Instance;
}
else
{
ins = BLInstance.GetInstanceByGuid(guid);
defaultCache.Remove(key);
defaultCache.Add(key, ins, CacheItemPriority.High, null, new SlidingTime(new TimeSpan(int.Parse(ConfigurationManager.AppSettings["ExpirationTimeHours"]), int.Parse(ConfigurationManager.AppSettings["ExpirationTimeMinutes"]), int.Parse(ConfigurationManager.AppSettings["ExpirationTimeSeconds"]))));
}
}
else
{
ins = BLInstance.GetInstanceByGuid(guid);
defaultCache.Add(key, ins, CacheItemPriority.High, null, new SlidingTime(new TimeSpan(int.Parse(ConfigurationManager.AppSettings["ExpirationTimeHours"]), int.Parse(ConfigurationManager.AppSettings["ExpirationTimeMinutes"]), int.Parse(ConfigurationManager.AppSettings["ExpirationTimeSeconds"]))));
}
return ins;
}