当手动将项目添加到缓存中时,是否可以使用使用缓存配置文件?
-
16-10-2019 - |
题
我在应用程序中使用了使用web.config中的输出缓存配置文件配置的输出缓存。能够在需要它的所有输出项上设置缓存,然后能够在一个地方调整所有缓存设置,这是非常方便的。
但是,我还在对某些项目的数据和逻辑层中实施缓存。如果我还可以引用配置文件而不是硬编码我想缓存的数据和逻辑项目的缓存参数,那将是方便缓存对象。
另类,我可以构建自己的配置部分,以列出手动添加项目的高速缓存配置文件。
解决方案
您可以获取执行此操作的输出缓存配置文件的列表:
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,当您以后要检索配置文件时,可以从缓存中提取。
不隶属于 StackOverflow