Joe
Joe

Reputation: 2097

How do I access a property created in global.asax.cs?

I'm reading two values from the web.config in the Application_Start of my Global.asax.cs. The string values from the web.config are assigned to their public properties, also defined in the Global.asax.cs .

How do I access the properties in the global.asax.cs file from another class, method, and namespace?

Update #1 This is more complicated than I thought (or maybe I'm just making it complicated). The class where I want to reference these properties in a plain ol' class library and I don't have access to httpcontext (or I don't know how to access it).

Upvotes: 5

Views: 7297

Answers (2)

Greg B
Greg B

Reputation: 14888

Cast the current application instance to your Global type and access the properties there.

var app = (Your.App.Namespace.Global)HttpContext.Current.ApplicationInstance;
var x = app.YourProperty;

Upvotes: 5

Patrice Calvé
Patrice Calvé

Reputation: 684

If the Global.asax.cs doesn't manipulate the values, then simply read the values from the web.config like you already do in global.asax.cs.

However, if the Global.asax.cs does manipulate the values, then you could write the values into the "Application" object.

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

        Application.Add("Foo", "Bar");

    }

Lastly, you can mark the property you want to expose from the Global as static.

    public static string Abc { get; set; }
    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup

        Abc = "123";

    }

Upvotes: 1

Related Questions