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.
In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created.
1)Private constructor to restrict instantiation of the class from other classes. 2)Private static variable of the same class that is the only instance of the class. 3)Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
To create the singleton class, we need to have static member of class, private constructor and static factory method. Static member: It gets memory only once because of static, itcontains the instance of the Singleton class. Private constructor: It will prevent to instantiate the Singleton class from outside the class.
The most popular approach is to implement a Singleton by creating a regular class and making sure it has: A private constructor. A static field containing its only instance. A static factory method for obtaining the instance.
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.
Store it in the HttpContext.Items
, that way it will be for each request.
HttpContext.Items - a Per-Request Cache Store
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With