在没有 HttpContext 的情况下在 asp.net 中获取 ApplicationState

发布于 2024-07-15 19:00:50 字数 319 浏览 3 评论 0原文

我有一个 Web 应用程序,它在 ApplicationState 中存储配置对象。 该对象包含数据库的连接字符串等。

有时我启动一个异步线程来执行一些长时间运行的任务,例如发送电子邮件和更新数据库。

但是,由于该线程没有 HttpContext,我无法获取配置对象。

我知道这种一切都依赖于 HttpContext 的设计很糟糕,但现在改变已经太晚了。 查看反射器,我发现 HttpContext 类仅使用静态内部类来获取 ApplicationState。 还有其他方法可以实现吗?

.net 中的所有这些内部类真的很烦人。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

街角迷惘 2024-07-22 19:00:50

当你启动线程时,只需将你喜欢的任何内容传递给你的线程即可。 使用 ParameterizedThreadStart 委托启动它,而不仅仅是 ThreadStart 委托。 您可以传递它 HttpContext.Current,或者将您希望线程拥有的信息捆绑在一起,然后传递它。

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.

桃扇骨 2024-07-22 19:00:50

如果您确实需要从异步处理程序访问应用程序状态(或类似的),您应该修改您的HttpApplication子类(例如Global.asax)以存储应用程序状态实例(this.Application) 到 Application_Start 期间的静态属性:

public static HttpApplicationStateWrapper State { get; private set; }

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

使用 DI 框架来注册此实例会更合适,但如果您有一个可用的框架,您可能可以避免使用总共用于存储配置的应用程序状态。 此外,.NET 中有一个配置框架可以直接满足这一需求,并提供从任何地方读取配置的能力。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文