【问题标题】:Strongly typed global data in ASP.Net Web PagesASP.Net 网页中的强类型全局数据
【发布时间】:2013-06-07 00:11:43
【问题描述】:

在 ASP.Net 网页中存储强类型全局数据的最佳实践是什么,对于每个请求都是唯一的?基本上我需要WebPageContext.Current.PageData 但强类型。

直到现在我想出了这样的东西:

public sealed class GlobalData
{
    public static GlobalData Current
    {
        get
        {
            if (WebPageContext.Current.PageData["GlobalData"] == null
                || WebPageContext.Current.PageData["GlobalData"].GetType() != typeof(GlobalData))
            {
                WebPageContext.Current.PageData["GlobalData"] = new GlobalData();
            }
            return WebPageContext.Current.PageData["GlobalData"];
        }
    }

    public string SomeData { get; set; }
}

这样我可以在每个页面上使用GlobalData.Current.SomeData 轻松访问我的数据。还是有更好的解决方案?

【问题讨论】:

    标签: c# asp.net webmatrix asp.net-webpages


    【解决方案1】:

    这是一个很好的方法。我会简化一点:

    public sealed class GlobalData
    {
        public static GlobalData Current
        {
            get
            {
                // soft cast using "as" which will return null if the type is not correct
                var globalData = WebPageContext.Current.PageData["GlobalData"] as GlobalData;
                if (globalData == null)
                {
                    // Need to instantiate
                    globalData = new GlobalData();
                    WebPageContext.Current.PageData["GlobalData"] = globalData;
                }
    
                return globalData;
            }
        }
    
        public string SomeData { get; set; }
    }
    

    【讨论】:

    • 感谢您的意见!既然我想让事情简单明了,你认为有办法摆脱这个静态的Current 属性吗?我宁愿只使用GlobalData.SomeData 访问我的数据。这可能适用于静态构造函数,但它不会为每个请求创建一个新的 GlobalData,对吧?
    • 您不能将 GlobalData 设为静态,因为这样所有用户都将共享一份副本。由于您希望每个用户都有一个副本,因此静态 Current 属性有效地实现了一个准单例,即每个请求一个。如果我是你,我会做的唯一改变是使用 HttpContext.Current.Items,它是一个存在于请求生命周期中的“缓存”,如果它对你可用的话。
    • 感谢您提供有关“as”运算符的提示,这对于在可能存在空值时保持代码清洁非常有用。
    猜你喜欢
    • 2010-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    相关资源
    最近更新 更多