【C#】強型別(Strong Type) 的Session用法

平常有時候用到Session時都是弱型別,管理很不易,當然Session能少用比較好。

找到資料想分享給大家強型別的Session用法,該作者是用單例模式(Singleton),主要管理Session類別如下。

SessionInfo

public class SessionInfo<Subclass>
    where Subclass : SessionInfo<Subclass>, new()
{
    private static string Key
    {
        get { return typeof(SessionInfo<Subclass>).FullName; }
    }

    private static Subclass Value
    {
        get { return (Subclass)HttpContext.Current.Session[Key]; }
        set { HttpContext.Current.Session[Key] = value; }
    }

    public static Subclass Current
    {
        get
        {
            var instance = Value;
            if (instance == null)
                lock (typeof(Subclass))
                {
                    instance = Value;
                    if (instance == null)
                        Value = instance = new Subclass();
                }

            return instance;
        }

    }
}

Model

public class Member : SessionInfo<Member>
{
    public string Name { get; set; }
    public int Age { get; set; }
}

設定值或取值

Member.Current.Name = "Vincent";
Member.Current.Age = 20;

string Name = Member.Current.Name;
int Age = Member.Current.Age;

就是這麼簡單,目前未發現有什麼缺點,確實不同使用者各Session互不影響。

參考資料

Source Code(Github)
Session with Style