简体   繁体   English

静态类asp.net mvc中的静态变量

[英]A static variable in static class asp.net mvc

I have a static class Data: 我有一个静态类数据:

 public static class Data
    {
        public static SqlConnection connexion;


        public static bool  Connect()
        {
                System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
                builder["Initial Catalog"] = "Upload";
                builder["Data Source"] = "base";
                builder["integrated Security"] = true;
                string connexionString = builder.ConnectionString;
                connexion = new SqlConnection(connexionString);
                try { connexion.Open(); return true; }
                catch { return false; }

        }
        public static  void Disconnect()
        {
            if (connexion != null) connexion.Close();
            connexion = null;
        }

 }

in an the action Home : 在行动中:

  public ActionResult Home()
        {
            Data.Connect();
            if (CompteModels.Connected)
            {
                ArrayList model = new ArrayList();

                ClientModels clients = new ClientModels();
                model.AddRange(clients.Client_List());

                AdminModels admins = new AdminModels();
                model.AddRange(admins.Admin_List());


                return View(model);
            }

            else return RedirectToAction("Login", "Account");
}

the client class: 客户端类:

 public List<ClientModels> Client_List()
        {
            List<ClientModels> l = new List<ClientModels>();

            using (Data.connexion)
            {

                string queryString = @"select Login, Password, Mail, Name, Tentatives from Compte where User_type_id in ( select Id from User_type where Fonction = 'Client')";

                SqlCommand command = new SqlCommand(queryString, Data.connexion);


                try
                {
                    SqlDataReader reader = command.ExecuteReader();


                    do
                    {

                        while (reader.Read())
                        {
                            ClientModels admin = new ClientModels { Login = reader.GetString(0), Password = reader.GetString(1), Mail = reader.GetString(2), Name = reader.GetString(3), Tentatives = reader.GetInt32(4)  };
                            l.Add(admin);


                        }
                    } while (reader.NextResult());

                    return l;



                }
                catch { return null; }

            }

For the function AdminList , the implementation is the same like Client_List but in the class Admin . 对于函数AdminList ,实现与Client_List相同,但在Admin类中。

The problem is in the static variable connexion : in the first function Client_List its value is correct and i get the list of the clients , but it's become null in the second function despite it is a static variable in static class !!! 问题在于静态变量connexion :在第一个函数Client_List它的值是正确的,我得到了客户端的列表,但它在第二个函数中变为null ,尽管它是静态类中的静态变量!

What is the reason of this alteration ? 这种改变的原因是什么? How can i fix it? 我该如何解决?

You're either setting connexion to null somewhere or not initializing it before you use it. 您要么在某处将connexion设置为null ,要么在使用它之前不将其初始化。

Most likely, one class is calling Disconnect which sets connexion to null, while another class assumes it's not null and tries to use it. 最有可能的是,一个类调用Disconnectconnexion设置为null,而另一个类则认为它不为null并尝试使用它。

As mentioned in the comments, keeping a static reference to a resource like a SqlConnection is not a good idea. 正如评论中所提到的,保持对像SqlConnection这样的资源的静态引用不是一个好主意。 If you want to re-use code you can create a static function that returns a new SqlConnection instance and make the connection string static, but having a static reference to a connection that's share across the entire web site will give you more problems that it's worth (as you're already seeing). 如果要重用代码,可以创建一个静态函数 ,该函数返回一个新的 SqlConnection实例并使连接字符串保持静态,但是对整个网站共享的连接进行静态引用会给你带来更多值得的问题。 (正如你已经看到的那样)。

One way to do it in a static function would be: 在静态函数中执行此操作的一种方法是:

public static SqlConnection GetConnection()
{
    System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
    builder["Initial Catalog"] = "Upload";
    builder["Data Source"] = "base";
    builder["integrated Security"] = true;
    string connexionString = builder.ConnectionString;
    connexion = new SqlConnection(connexionString);

    return connexion; 
}

Your client code would then look something like: 您的客户端代码将如下所示:

using (SqlConnection conn = Data.GetConnection())

This is a bad idea, as others have already mentioned. 正如其他人已经提到的那样,这是一个坏主意。

You should simply create and open a connection when needed, and dispose it afterwards: 您只需在需要时创建并打开连接,然后再将其处理:

using (SqlConnection connection = new SqlConnection(connectionString)) 
{    
    connection.Open();
    // ... now use it
}

Of course, there are other patterns, that hide this mechanism, but that might be overkill in your case. 当然,还有其他模式,隐藏这种机制,但在你的情况下可能是矫枉过正。

Your using statement disposes of the connexion using the IDisposable interface 您的using语句使用IDisposable接口处理连接

 public List<ClientModels> Client_List()
 {
      List<ClientModels> l = new List<ClientModels>();

      using (Data.connexion) <--- here
}

Change this to create a new connection 更改此项以创建新连接

 public List<ClientModels> Client_List()
 {
      List<ClientModels> l = new List<ClientModels>();

      using (var connection = Data.CreateConnexion())
}

similar to this 与此类似

 public static class Data
 {
     public static SqlConnection CreateConnection()
     {
        System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
            builder["Initial Catalog"] = "Upload";
            builder["Data Source"] = "base";
            builder["integrated Security"] = true;
            string connexionString = builder.ConnectionString;
            var connexion = new SqlConnection(connexionString);
            connexion.Open(); 
            return connexion; 

     }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM