gpt4 book ai didi

session - 静态属性间歇性地失去其值(value)?

转载 作者:行者123 更新时间:2023-12-03 05:08:58 26 4
gpt4 key购买 nike

以下设计是否存在根本性错误,或者有人能明白为什么静态属性有时会丢失其值吗?

我有一个包含 AppConfig 类的类库项目;此类由 Webforms 项目使用。

AppConfig类的框架如下:

Public Class AppConfig
Implements IConfigurationSectionHandler

Private Const C_KEY1 As String = "WebConfig.Key.1"
Private Const C_KEY2 As String = "WebConfig.Key.2"
Private Const C_KEY1_DEFAULT_VALUE as string = "Key1defaultVal"
Private Const C_KEY2_DEFAULT_VALUE as string = "Key2defaultVal"

Private Shared m_field1 As String
Private Shared m_field2 As String

Public Shared ReadOnly Property ConfigValue1() As String
Get
ConfigValue1= m_field1
End Get
End Property

Public Shared ReadOnly Property ConfigValue2() As String
Get
ConfigValue2 = m_field2
End Get
End Property


Public Shared Sub OnApplicationStart()
m_field1 = ReadSetting(C_KEY1, C_KEY1_DEFAULT_VALUE)
m_field2 = ReadSetting(C_KEY2, C_KEY1_DEFAULT_VALUE)
End Sub

Public Overloads Shared Function ReadSetting(ByVal key As String, ByVal defaultValue As String) As String
Try
Dim setting As String = System.Configuration.ConfigurationManager.AppSettings(key)
If setting Is Nothing Then
ReadSetting = defaultValue
Else
ReadSetting = setting
End If
Catch
ReadSetting = defaultValue
End Try
End Function

Public Function Create(ByVal parent As Object, ByVal configContext As Object, ByVal section As System.Xml.XmlNode) As Object Implements System.Configuration.IConfigurationSectionHandler.Create
Dim objSettings As NameValueCollection
Dim objHandler As NameValueSectionHandler

objHandler = New NameValueSectionHandler
objSettings = CType(objHandler.Create(parent, configContext, section), NameValueCollection)

Return 1
End Function

End Class

静态属性在应用程序启动时从 Global.asax 的 Application_Start 事件中设置一次

Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)

//Fires when the application is started
AppConfig.OnApplicationStart()

End Sub

此后,每当我们想要从任何地方访问 Web.Config 中的值时,例如aspx页面代码隐藏或另一个类或引用的类,我们只需调用静态属性。

例如,

AppConfig.ConfigValue1()
AppConfig.ConfigValue2()

这将返回存储在静态支持字段 m_field1、m_field2 中的值

问题是有时这些值是空字符串,而 Web.Config 条目显然有值。

上述设计是否存在根本性错误,或者期望静态属性在应用程序 session 的生命周期内保持其值是否合理?

最佳答案

我会添加一些调试/跟踪输出,也许可以看看发生了什么。确保也找出任何异常情况。

我还会更改属性返回以使用现代语法(我不确定它的支持程度如何)。

return defaultValue

而不是:

ReadSetting = defaultValue

关于session - 静态属性间歇性地失去其值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2854906/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com