开发者

Is there a way to use use a cache profile when manually adding items to the cache?

I have output caching in my application configured using output cache profiles in the web.config. It is very convenient to be able to setup caching on all the output items that need it and then be able to adjust all the cache settings in one place.

However, I am also implementing cachin开发者_开发百科g in my data and logic layers for certain items. It would be convenient if I could also reference a profile instead of hard coding the caching parameters for data and logic items I want to cache, but there doesn't seem to be a way to reference a profile in the Insert() method on the cache object.

Alternativly, I could build my own configuration section to list cache profiles for manually added items.


You can get a list of your output cache profiles doing this:

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;
        }
    }
}

And then use it on your insert:

/// <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
    }


If you are referring to C#'s Cache.Insert object you can append a GUID to the key so that every profile has a corresponding GUID which you can extract out of the cache when you want to retrieve the profile later on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜