In my projects, I used connection string inside non-static classes, and It works fine. But now I'm developing a project that uses connection string inside static classes. In the code below the Catch block will throw an error as shown below:
NullReferenceException: Object reference not set to an instance of an object.
If I comment out this line "Throw" it works fine, but I want to understand what went wrong in my code.
DataAccess
class:
public class DataAccess
{
static string connstr = ConfigurationManager.ConnectionStrings["DbSystem2018"].ConnectionString;
public static object GetSingleAnswer(string sql, List<SqlParameter> PList)
{
object obj = null;
SqlConnection conn = new SqlConnection(connstr);
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
if (PList != null)
{
foreach (SqlParameter p in PList)
cmd.Parameters.Add(p);
}
obj = cmd.ExecuteScalar();
}
catch (Exception ex)
{
throw; // THIS LINE THROW THE NullReferenceException Error
}
finally
{
conn.Close();
}
return obj;
}
}
The problem is with using static connection string field inside static classes. So, is there any way to solve this issue without using any non static public classes?
Updated:
Please notice the following:
I don't want to use non-static methods, my question is how we can fix this using static methods.
When we use static field, we initialize it right away:
static string v1 = "hello";
but why the initialization for the following code throw null before returning the actual connection string?
static string connstr = ConfigurationManager.ConnectionStrings["DbSystem2018"].ConnectionString;
By the way, the connection string inside the web.config
is fine.
This:
System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
if (config.ConnectionStrings.ConnectionStrings.Count > 0)
{
var connString = config.ConnectionStrings.ConnectionStrings[nameOfConnectionString].ToString();
return connString;
}
Is copy paste from: https://www.codeproject.com/Articles/1012286/Read-web-config-Settings
The problem is that you're accessing a config file. Those have to be converted to an object before they are accesible. This is what the code above does.