Pregunta

I got a webapp that stores a config object in ApplicationState. This object contains the connection string to the database among other things.

Sometimes i start a async thread to do a few longer running tasks, like sending emails and updating the database.

However since this thread don't have a HttpContext i can't get at the config object.

I know this design that everything depends on HttpContext is bad, but thats too late to change now. Looking at reflector i see that the HttpContext class just uses a static internal class to get the ApplicationState. Is there any other way to get at it?

All those internal classes in .net are really annoying.

¿Fue útil?

Solución

Just pass whatever you like to your thread when you start it. Use a ParameterizedThreadStart delegate to start it instead of just a ThreadStart delegate. You could either pass it HttpContext.Current, or else bundle together the information you want your thread to have, and pass it.

Otros consejos

If you really need access to Application State (or similar) from async handlers you should modify your HttpApplication subclass (e.g. Global.asax) to store the Application State instance (this.Application) to a static property during Application_Start:

public static HttpApplicationStateWrapper State { get; private set; }

protected void Application_Start()
{
    State = new HttpApplicationStateWrapper(this.Application);
}

It would be more appropriate to use a DI framework to register this instance, but if you have one available you could probably avoid the use of Application State altogether for storing config. Further, there is a configuration framework in .NET that directly addresses this need and provides the ability to read configuration from anywhere.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top