views:

32

answers:

2

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

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.

+5  A: 

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.

Mark_Carrington
+4  A: 

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).

Dean Harding