I wanted a pattern to manage web.config appsettings. I want to be able to have a default setting if the config setting was missing. I also wanted the check for the value in the config file to happen only once, not each time the the value is retrieved.
Public NotInheritable Class ExternalReportRequestBL
''' <summary>
''' The default value for max number of request attempts
''' </summary>
''' <remarks></remarks>
Private Shared _ReportRequestMaxExecuteAttemptDefault As Integer
Shared Sub New()
If Not Integer.TryParse(ConfigurationManager.AppSettings("ReportRequestMaxExecuteAttempt"), ExternalReportRequestBL._ReportRequestMaxExecuteAttemptDefault) Then
_ReportRequestMaxExecuteAttemptDefault = 10
End If
End Sub
Friend Shared ReadOnly Property MaxNumberOfTries As Integer
Get
Return ExternalReportRequestBL._ReportRequestMaxExecuteAttemptDefault
End Get
End Property
End Class
Now, I can access the variable from anywhere in the assembly:
ExternalReportRequestBL.MaxNumberOfTries
What are your thoughts?
-
\$\begingroup\$ May I ask what lend you to wanting this? Typically, those settings are specifically for specifying defaults and configuration settings. I'm smelling an XY problem, but I don't yet understand what your real problem is. \$\endgroup\$RubberDuck– RubberDuck2016年05月15日 13:58:51 +00:00Commented May 15, 2016 at 13:58
1 Answer 1
Integer.TryParse
will overwrite the value of that shared property with 0 if the value is not there. Use something like this instead:
Shared Sub New()
Dim parsed As Integer
If Integer.TryParse(ConfigurationManager.AppSettings("ReportRequestMaxExecuteAttempt"), parsed) Then
_ReportRequestMaxExecuteAttemptDefault = parsed
End If
End Sub
-
\$\begingroup\$ You are correct. Changed my question accordingly. \$\endgroup\$Shai Cohen– Shai Cohen2012年04月26日 23:47:21 +00:00Commented Apr 26, 2012 at 23:47