次のように HttpContext.Current.Items を使用して実装された、リクエストによるキャッシュがあります。
private static readonly Lazy<CacheCurrentCall> lazy =
new Lazy<CacheCurrentCall>(() => new CacheCurrentCall());
public static CacheCurrentCall Instance
{
get
{
IDictionary items = HttpContext.Current.Items;
if (!items.Contains("CacheCurrentCall"))
{
items["CacheCurrentCall"] = new CacheCurrentCall();
}
return items["CacheCurrentCall"] as CacheCurrentCall;
}
}
private CacheCurrentCall()
{
}
public void Add<T>(T o, string key, int cacheDurationSeconds = 0)
{
HttpContext.Current.Items.Add(key, o);
}
public void Clear(string key)
{
HttpContext.Current.Items.Remove(key);
}
public bool Exists(string key)
{
return HttpContext.Current.Items[key] != null;
}
public bool Get<T>(string key, out T value)
{
try
{
if (!Exists(key))
{
value = default(T);
return false;
}
value = (T)HttpContext.Current.Items[key];
}
catch
{
value = default(T);
return false;
}
return true;
}
ここで、特定の文字列で始まるすべてのキーを削除する必要があるため、このような方法を考えていました
public IEnumerable<string> GetKey (Func<string, bool> condition)
次に、結果をループしてクリアします(ラムダ式を受け入れる Clear で直接クリアすることもできます)。しかし、実際に可能であれば、そのようなメソッドを実装しようとして迷っています。
何か助けはありますか?
ありがとう
編集:
Servy、私は試していました(やみくもにいくつかのことを試してきましたが、多かれ少なかれこの道をたどっています)
public IEnumerable<string> GetKeys(Func<string, bool> condition)
{
List<string> list = new List<string>();
foreach (var key in HttpContext.Current.Items.Keys)
{
if (condition(key as string))
{
list.Add(key as string);
}
}
return list;
}
しかし、私は得ています:
オブジェクト参照がオブジェクト インスタンスに設定されていません
私は今試してみます.pswgはおそらくうまくいくだけでなく、私の目にははるかにエレガントです.
2番目の編集:
pswg ソリューションを少し変更する必要がありました。キャッシュには文字列を保存するのではなく、他の種類のオブジェクトを保存するので、現在はこれを使用しています
public IEnumerable<string> GetKeys (Func<string, bool> condition)
{
return HttpContext.Current.Items
.Cast<DictionaryEntry>()
.Where(e => e.Key is string && condition(e.Key as string))
.Select(e => e.Key as string);
}
そして、キャッシュをクリアするための呼び出しは、たとえばこれです
public void ClearCache()
{
var ownedItemSummaryKeys = CacheCurrentCall.Instance.GetKeys(k => k.Contains("OwnedItemSummaryCurrent"));
foreach (var ownedItemSummaryKey in ownedItemSummaryKeys.ToList())
{
CacheCurrentCall.Instance.Clear(ownedItemSummaryKey);
}
}