【问题标题】:Is there a way to use use a cache profile when manually adding items to the cache?手动将项目添加到缓存时,有没有办法使用缓存配置文件?
【发布时间】:2011-01-21 17:10:24
【问题描述】:

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

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

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

【问题讨论】:

    标签: asp.net asp.net-caching asp.net-cache


    【解决方案1】:

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

    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
        }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2011-07-15
        • 2021-12-31
        • 2019-08-09
        • 1970-01-01
        • 1970-01-01
        • 2017-03-21
        • 2014-05-11
        • 2022-01-04
        • 2012-06-27
        相关资源
        最近更新 更多