このコードを謙虚に再利用した場所を一生覚えていませんが、かなりいいです:
using System;
using System.Web;
namespace Project.Web.UI.Domain
{
public abstract class SessionBase<T> where T : class, new()
{
private static readonly Object _padlock = new Object();
private static string Key
{
get { return typeof(SessionBase<T>).FullName; }
}
public static T Current
{
get
{
var instance = HttpContext.Current.Session[Key] as T;
lock (SessionBase<T>._padlock)
{
if (instance == null)
{
HttpContext.Current.Session[Key]
= instance
= new T();
}
}
return instance;
}
}
public static void Clear()
{
var instance = HttpContext.Current.Session[Key] as T;
if (instance != null)
{
lock (SessionBase<T>._padlock)
{
HttpContext.Current.Session[Key] = null;
}
}
}
}
}
その背後にある考え方は 2 つあります。作成されたタイプは、必要な唯一のタイプである必要があります。基本的には、強く型付けされた大きなラッパーです。したがって、情報を拡張し続けたいオブジェクトがあります。
public class MyClass
{
public MyClass()
public string Blah1 { get; set; }
}
次に、拡張する道をMyClass
たどり、すべてのキー値を覚える必要はなく、静的クラスの AppSettings または Const 変数に格納します。保存するものを定義するだけです。
public class MyClassSession : SessionBase<MyClass>
{
}
プログラムのどこでも、クラスを使用するだけです。
// Any Asp.Net method (webforms or mvc)
public void SetValueMethod()
{
MyClassSesssion.Current.Blah1 = "asdf";
}
public string GetValueMethod()
{
return MyClassSession.Current.Blah1;
}