【问题标题】:The right method of sharing database variables (asp.net)共享数据库变量的正确方法(asp.net)
【发布时间】:2010-04-21 07:35:13
【问题描述】:

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

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

如果我从声明中删除“公共共享”,则不会在我的页面中提取变量。谁能告诉我正确的分享方式?

非常感谢, 菲尔。

【问题讨论】:

    标签: asp.net database declaration fxcop code-sharing


    【解决方案1】:

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

    Private Sub New()
    End Sub
    

    这将防止任何代码在类本身之外创建Vars 类的实例。

    【讨论】:

      【解决方案2】:

      这是您班级中的唯一代码吗?

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

      你在这里得到它的方式,它不是线程安全的(例如,如果两个人同时发出请求,事情就会变得真的搞砸了)。 p>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-01
        • 1970-01-01
        • 2019-06-27
        • 1970-01-01
        • 2020-08-19
        • 2019-06-10
        • 1970-01-01
        相关资源
        最近更新 更多