Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single instance of a class per HTTP request

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.

like image 966
h3rj4n Avatar asked Nov 23 '11 13:11

h3rj4n


People also ask

Is a single instance of a class?

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.

How do you ensure only one instance in a singleton class?

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.

How do I create a single instance?

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.

What is the most common method to obtain a singleton?

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.


2 Answers

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.

like image 180
AakashM Avatar answered Sep 20 '22 13:09

AakashM


Store it in the HttpContext.Items, that way it will be for each request.

HttpContext.Items - a Per-Request Cache Store

like image 42
rick schott Avatar answered Sep 21 '22 13:09

rick schott