每个 HTTP 请求的类的单个实例

发布于 2024-12-17 13:14:57 字数 577 浏览 2 评论 0原文

为了调试我的 ASP.NET 应用程序,我创建了一个名为 MessageHandling.cs 的类。此时它是一个单例模式,但我希望它成为每个请求的一个实例。

我的 mssqlDb 类用诸如“Db 连接”、“数据插入”之类的消息填充 MessagesHandling 类。处理完 apsx 页面的所有事件后,Page_LoadComplete() 事件中的 createFile.apsx.cs 会读取 MessageHandling 类。所有错误和消息都会显示给用户。

此时系统进入调试状态。此时的问题是,发送请求后 MessageHandling 并未清空,并且错误也显示在第二个浏览器上,而不执行任何操作。我还希望能够使用该系统向最终用户显示消息,例如:“博客已创建”。

我的问题的基本内容如下:
A 类 创建B 类
C 类 读取B 类

单例不起作用,因为它不是针对每个用户/会话/请求的。所以我需要另一种方法。

To debug my ASP.NET application I created a class called MessageHandling.cs. At this point it's a singleton pattern but I want it to be an instance per request.

My mssqlDb class fills the MessagesHandling class with messages like: 'Db connected', 'Data inserted' and stuff like that. After all the Events of the apsx page are processed the MessageHandling class is read by createFile.apsx.cs in the event Page_LoadComplete(). All the errors and messages will be showm to the user.

At this point the system works for debugging. The problem at this point is that the MessageHandling isn't emptied after the request has been send and the errors are also shown on the second browser without doing anything. I also want to be able to use this system for showing messages to the end users like: "Blog created".

The basic of my problem is the following:
Class A creates Class B
Class C reads Class B

The singleton doesn't work because it's not per user / session / request. So I need an other method.

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

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

发布评论

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

评论(3

浅唱々樱花落 2024-12-24 13:14:57

HttpContext.Current 是当前请求的 HttpContext 对象。它有一个 Items 属性,它是一个从 objectobjectIDictionary。您可以在其中放置任何您喜欢的内容,它将与当前请求相关联。

HttpContext.Current is the HttpContext object for the current request. It has an Items property which is an IDictionary from object to object. You can put anything you like in there, and it will be tied to the current request.

九命猫 2024-12-24 13:14:57

您可以检查单例的构造函数以查看该对象是否存在于会话中吗?如果没有,创建它然后返回它?

private Singleton()
{
    // do whatever
}

public Singleton GetMySingleton()
{
    if(HttpContext.Current.Items["MyCustomSingleton"] == null)
        HttpContext.Current.Items["MyCustomSingleton"] = new Singleton();
    //

    return (Singleton)HttpContext.Current.Items["MyCustomSingleton"];
}

Can you check in the constructor of your singleton to see if that object exists in the session? If not, create it and then return it?

private Singleton()
{
    // do whatever
}

public Singleton GetMySingleton()
{
    if(HttpContext.Current.Items["MyCustomSingleton"] == null)
        HttpContext.Current.Items["MyCustomSingleton"] = new Singleton();
    //

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