Enterprise Library 的配置是通过配置工具实现的,所以缓存的配置也是需要通过这个配置工具实现。Enterprise Library 的缓存实现有三种方式;
1)Null backing store 存储策略
特点:数据保存在内存里,所以只要是打算重启之后不需要的数据都可以存在这个地方
2)Isolated storage 存储策略
特点:我认为是保存在文件中,这个文件只有通过对应的处理机制才能访问,否则无法访问,也就是说使用起来比较有限制,因为你看不见摸不着的数据。
3)Database Cache storeage 存储策略
特点:保存在数据库里,需要通过编写存储过程来实现的存储策略
实现方式:
1)Null backing store 存储策略
点击随便一个可以打开的EntLib Config .NET 4 工具就能看到配置的界面了,界面如下
保存生成的文件,保存成 .config 格式的
<configuration>
<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="Cache Manager">
<cacheManagers>
<add name="Cache Manager" type="Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
expirationPollFrequencyInSeconds="60" 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>
</configuration>
这里的配置文件需要复制内容到app.config 文件中,配置的时候最好写在最前面,因为我发现如果放在最后面
会弹出一个,让你选择文件的对话框。保存完之后就剩下写代码了,
首先需要到安装文件夹中寻找需要的dll文件Microsoft.Practices.EnterpriseLibrary.Caching.dll 然后添加引用,
在文件上方添加命名空间using Microsoft.Practices.EnterpriseLibrary.Caching;
代码的编写如下:
static void Main(string[] args)
{
//创建CacheManager
CacheManager cacheManager = (CacheManager)CacheFactory.GetCacheManager();
//添加缓存项
cacheManager.Add("MyDataReader", "123");
//获取缓存项
string str = (String)cacheManager.GetData("MyDataReader");
//打印
Console.WriteLine(str);
Console.Read();
}