Question

Im facing a problem in one of MVC projects, that problem is about retrieving values from Application State object.

I am storing some value into the Application state in Application_Start() method of Global.axas.cs in this manner:

//var str = Obj.DecryptString(ConfigurationManager.ConnectionStrings["ConStr"].ToString());
//Application["connString"] = str;

Application["connString"] = Obj.DecryptString(ConfigurationManager.ConnectionStrings["ConStr"].ToString());

I have made sure the value from web.config has been successfully retrieve at this point through debugging.

After this step I’m trying to retrieve this value in one of my Model Class in this manner:

var conn = new SqlConnection(Application["connString"].ToString());

But here I’m getting a NullReferenceException Object reference not set to an instance of an object.

Now this is very confusing for me here that if the value has been successfully retrieved and stored in AapplicationState at the point of Application_Start() than why isn’t it available in my model class, aren't the ApplciatiopnSate available throughout the application?

Was it helpful?

Solution

My suggestion is not to keep the connection string in the Application variable. Rather you can declare a static method which can return the connection string.Store the connection string in a static variable as shown below

public class Utility
{
    static string connectionString;    
    public static string GetConnectionString()
    {
        if(string.IsNullOrEmpty(connectionString))
            connectionString = Obj.DecryptString(ConfigurationManager.ConnectionStrings["ConStr"].ToString());
        return connectionString;
    }
}

Configuration files are cached, henceforth you need not worry about performance of reading the files every time the method is called

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top