2

我在我的应用程序中使用 web.config 中的输出缓存配置文件配置了输出缓存。能够在所有需要它的输出项上设置缓存,然后能够在一个地方调整所有缓存设置,这非常方便。

但是,我还在我的数据和逻辑层中为某些项目实现缓存。如果我还可以引用配置文件而不是硬编码要缓存的数据和逻辑项的缓存参数,那会很方便,但似乎没有办法在 Insert() 方法中引用配置文件缓存对象。

或者,我可以构建自己的配置部分来列出手动添加项目的缓存配置文件。

4

2 回答 2

3

您可以通过以下方式获取输出缓存配置文件的列表:

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
    }
于 2011-01-21T18:06:25.517 回答
0

如果您指的是 C# 的Cache.Insert对象,您可以将 GUID 附加到键中,以便每个配置文件都有一个相应的 GUID,您可以在以后想要检索配置文件时从缓存中提取该 GUID。

于 2011-01-21T17:37:43.967 回答