共享数据库变量的正确方法(asp.net)

共享数据库变量的正确方法(asp.net),asp.net,database,declaration,fxcop,code-sharing,Asp.net,Database,Declaration,Fxcop,Code Sharing,我一直在使用以下代码共享数据库变量: 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(co

我一直在使用以下代码共享数据库变量:

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
然后,我将其导入到我的项目中,如下所示:

Imports DataAccessVariables.Vars
当我使用FXCop查看站点时,我收到以下消息:

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)
}
如果我从声明中删除“Public Shared”,那么这些变量就不会出现在我的页面中。有人能告诉我分享它们的正确方法吗

非常感谢,
菲尔。

此错误并没有告诉您删除公共共享变量。相反,它让您知道可以创建
Vars
类的新实例,即使它只包含
共享的
成员。要解决此问题,请定义专用构造函数:

Private Sub New()
End Sub
这将防止任何代码在类本身之外创建
Vars
类的实例。

这是类中唯一的代码吗

此外,不应创建全局(静态)
SqlConnection
。只需按需创建
SqlConnection
SqlCommand
对象。连接池将确保一次只进行一个物理数据库连接

按照这里的方式,它不是线程安全的(例如,如果两个人同时提出请求,事情会变得非常糟糕)