singleton classes in web application

A

Anurag K

i have created a singleton class in a class file in my asp.net web
application.
this class is a singleton class.

the code is:
public class singletonclass
{
private static singletonclass sc = null;

private singletonclass(string path)
{
using (FileStream fs = File.OpenWrite(path))
{
Byte[] info =
new UTF8Encoding(true).GetBytes("new instance created");

// Add some information to the file.
fs.Write(info, 0, info.Length);
}
}

public static singletonclass getsingletonclassinstance(string path)
{
if (sc == null)
{
sc = new singletonclass(path);
}
return sc;
}
}
there is a single web form in my application. the code in the page
load of my webform is:
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
singletonclass.getsingletonclassinstance(Server.MapPath(".")+@"\write.txt");
}

the issue here is even if i run different browser instances i am
getting only a single entry in my text file. my understanding is
different web requests do not share memory and so there should have
been a single object for each request. if within a web request there
are multiple calls to the singletonclass.getsingletonclassinstance()
method, reference to the same object should be returned.

if anybody got what i am trying to convey then please reply.
 
S

Scott Allen

There is only one instance of the static member sc in your class. The
problem you may run into is that it could be initialized by more than
one thread (it is not thread safe as written).

Good information in this article:
Implementing Singleton in C#
http://msdn.microsoft.com/library/d...n-us/dnpatterns/html/ImpSingletonInCsharp.asp

Pay careful attention to the volatile keyword when looking at the
source of the article - it is needed in the member declaration.

What I am not understanding is your description of the behavior.
Multiple web requests will all see the same reference for sc once it
has been safely initialized. The private constructor will run exactly
once during the lifetime of the appdomain, and you should see only one
entry in the file.

Does that make sense or am I not understanding the question?
 
J

Jarmo Muukka

Hello,

Looks like you want a singleton per web request. It is not possible in a way
you're trying to do it. I don't know is there a way to do it - other than
creating it e.g. in Page.OnInit or in similar place and disposing it in
Page.OnUnload.

Singleton is really a singleton. Only one instance is living at one time in
the application. And, all clients and sessions and web requests share the
same application.

JMu
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top