0

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?

dove
  • 20,469
  • 14
  • 82
  • 108
SajjadHashmi
  • 3,795
  • 2
  • 19
  • 22
  • Just been through this: http://www.codeproject.com/Articles/87316/A-walkthrough-to-Application-State and I cannot see a difference between how you are using it. – Luke Duddridge Nov 15 '12 at 12:32

1 Answers1

0

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

ygoku
  • 179
  • 1
  • 4
  • One of the main reasons I’m putting it there is as you see it in encrypted format and needs to be decrypted before use, so I don’t want this `reading`, `decryption` to happen every time a data connection has to be made in some method which will increase the time and would be redundant practice. – SajjadHashmi Nov 15 '12 at 12:33
  • Thankyou for providing the alternative but even if configuration files are cached the `DecryptString` method will have to be called every time this method is called? My main concern is to avoid using this heavy method as much as possible. – SajjadHashmi Nov 15 '12 at 12:46