开发者

The right method of sharing database variables (asp.net)

I have been sharing database variables using the following code:

Namespace DataAccessVariables
    Public Class Vars
        Public Shared s As String
        Public Shared con As String = WebConfigurationManager.ConnectionStrings("Dev").ToString()
        Public Shared c As New SqlConnection(con)
        Public Shared x As New SqlCommand(s, c)
    End Class
End Namespace

I then import this to my project like this:

Imports DataAccessVariables.Vars
开发者_如何学C

When I check the site with FXCop, I get this message:

Error, Certainty 90, for StaticHolderTypesShouldNotHaveConstructors
{
    Target       : DBVars  (IntrospectionTargetType)
    Resolution   : "Remove the public constructors from 'Vars'."
    Help         : http://msdn2.microsoft.com/library/ms182169(VS.90).aspx  (String)
    Category     : Microsoft.Design  (String)
    CheckId      : CA1053  (String)
    RuleFile     : Design Rules  (String)
    Info         : "Instances of types that define only static members 
                   do not need to be created. Many compilers will automatically 
                   add a public default constructor if no constructor 
                   is specified. To prevent this, adding an empty private 
                   constructor may be required."
    Created      : 2010/04/20 01:25:16 PM  (DateTime)
    LastSeen     : 2010/04/21 07:17:46 AM  (DateTime)
    Status       : Active  (MessageStatus)
    Fix Category : Breaking  (FixCategories)
}

If I remove the 'Public Shared' from the declarations, then the variables are not picked up in my pages. Can anyone show me the correct way of sharing them?

Thanks a lot, Phil.


This error isn't telling you to remove the Public Shared variables. Instead it's letting you know that it is possible to create a new instance of your Vars class, even though it includes only Shared members. To resolve the issue, define a private constructor:

Private Sub New()
End Sub

This will prevent any code creating an instance of the Vars class outside of the class itself.


Is that the only code in your class?

Also, you should not create a global (static) SqlConnection. Simply create the SqlConnection and SqlCommand objects on-demand. Connection pooling will ensure that only one physical database connection is made at a time.

The way you've got it here, it's not thread-safe (if two people make a request at the same time, for example, things are going to get really screwy).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜