Reputation: 175
I have two projects in a solution. A C# class library project encapsulate logic and a asp.net website for view. Here is the logic:
public static class LoginHandler
{
private static string _connectionString = Data Source=.;Initial Catalog=ASP;Integrated Security=True"
private static SqlConnection Connection;
static LoginHandler()
{
Connection = new SqlConnection(ConnectionString);
}
public static User StudentLogin(string username, string password)
{
using (Connection)
{
.........
}
}
}
Everything goes well until I call StudentLogin method for the second time.
I get an InvalidOperationException says that the ConnectionString Property of Connection is not initialized. (ConnectionString is "" through the watch window)
My question is, since static members are initialized only once(this case,in the static constructor), how could the ConnectionString property changed?
Or,is the using statement which calls the IDisposible.Dispose() to be blamed?
Upvotes: 0
Views: 54
Reputation: 14896
Or,is the using statement which calls the IDisposible.Dispose() to be blamed?
Yes. You should create a new connection each time the StudentLogin
method is called. You don't even need the static field to keep a reference to it.
public static User StudentLogin(string username, string password)
{
using (var connection = new SqlConnection(ConnectionString))
{
}
}
Upvotes: 2