3

Is it possible to create a class instance on Application_Start that can be used in all controllers?

I would like to be able to create for example:

var globalHelper = new LoadsStuff();

and then in my Action methods:

globalHelper.GetInfoFor("key");

My Helper class loads a fairly big XML file to memory and I would like to do that only once.

3
  • Are you using MVC? If you are, you should indicate that in your tags. Commented Jun 1, 2011 at 13:41
  • I did but a admin change the tags to asp.net, I just fixed :) Commented Jun 1, 2011 at 13:42
  • 1
    this sound suspiciously like you want to use dependency injection. have a look at ninject mvc weblogs.asp.net/shijuvarghese/archive/2010/04/30/… Commented Jun 1, 2011 at 13:44

3 Answers 3

4

Use application variables:

Application["GlobalHelper"] = new LoadsStuff();

((LoadsStuff) Application["GlobalHelper"]).GetInfoFor("key");

Refer to:

ASP.NET Application State Overview

Sign up to request clarification or add additional context in comments.

3 Comments

The Application is not available in the controller, are you sure this is correct?
@Bjarki Heiðar: Try HttpContext.Current.Application.
It's HttpContext.Application, Thank you.
1

What if you put your XML file Application level object in Application_Start event ?

void Application_Start(object sender, EventArgs e)
{
     Application[""] = //
}

Comments

0

Yes I think you can. I have not tried this, but something like:

ManagedWebSessionContext.Bind(HttpContext.Current, globalHelper)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.