手动添加项目到缓存时有没有办法使用使用缓存配置文件?
问题描述:
我在使用web.config中的输出缓存配置文件配置的应用程序中输出缓存。能够在需要它的所有输出项目上设置缓存并且能够在一个地方调整所有缓存设置非常方便。手动添加项目到缓存时有没有办法使用使用缓存配置文件?
但是,我也在我的数据和逻辑层实现某些项目的缓存。如果我也可以引用一个配置文件而不是对我想要缓存的数据和逻辑项的缓存参数进行硬编码,但是似乎没有办法在Insert()方法中引用一个配置文件缓存对象。
另外,我可以建立自己的配置部分列出手动添加项目的缓存配置文件。
答
你可以得到你的输出缓存配置文件列表,这样做:
private Dictionary<string, OutputCacheProfile> _outputCacheProfiles;
/// <summary>
/// Initializes <see cref="OutputCacheProfiles"/> using the settings found in
/// "system.web\caching\outputCacheSettings"
/// </summary>
void InitializeOutputCacheProfiles(
System.Configuration.Configuration appConfig,
NameValueCollection providerConfig)
{
_outputCacheProfiles = new Dictionary<string, OutputCacheProfile>();
OutputCacheSettingsSection outputCacheSettings =
(OutputCacheSettingsSection)appConfig.GetSection("system.web/caching/outputCacheSettings");
if(outputCacheSettings != null)
{
foreach(OutputCacheProfile profile in outputCacheSettings.OutputCacheProfiles)
{
_outputCacheProfiles[profile.Name] = profile;
}
}
}
,然后用它在你插入:
/// <summary>
/// Gets the output cache profile with the specified name
/// </summary>
public OutputCacheProfile GetOutputCacheProfile(string name)
{
if(!_outputCacheProfiles.ContainsKey(name))
{
throw new ArgumentException(String.Format("The output cache profile '{0}' is not registered", name));
}
return _outputCacheProfiles[name];
}
/// <summary>
/// Inserts the key/value pair using the specifications of the output cache profile
/// </summary>
public void InsertItemUsing(string outputCacheProfileName, string key, object value)
{
OutputCacheProfile profile = GetOutputCacheProfile(outputCacheProfileName);
//Get settings from profile to use on your insert instead of hard coding them
}
答
如果您指的是C#的Cache.Insert
对象,则可以将GUID附加到该键,以便每个配置文件都有相应的GUID,您可以在稍后检索配置文件时从缓存中提取该GUID。