April 2007 - Posts

.NET interview question - when is a singleton not a singleton?

I've read some posts lately with questions people use to ask or have been asked during a job interview, so I wanted to post a tricky question too.

I've talked about singletons in the past, and what we use to think is that a classic singleton class has to be unique into a specific AppDomain. Let's take this simple implementation of the singleton pattern, which is thread safe, too: [edit: made the class sealed to avoid confusion]

public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();

// Private constructor to prevent external instantiation
private Singleton()
{}

public static Singleton Instance
{
get { return instance; }
}
}

There's at least one situation where you can find yourself having multiple instances of the singleton class in the same AppDomain, can you tell when?

kick it on DotNetKicks.com

Posted 30 April 2007 01:14 AM by simoneb | 11 comment(s)
Filed under:
DotNetSlackers is growing and paying you!

DotNetSlackers.com is one of the best .NET news providers there are, it aggregates a lot of feeds from the most interesting bloggers out there and provides them either as a dynamic aggregate RSS feed or a newsletter service which are much easier to follow since grouping all the interesting stuff into a single channel, evolving continuously and adding new content day by day. The service is highly customizable since you can choose to filter the content you receive by tags and keywords.

I got to know DNS about a year ago when following a link on Scott Guthrie's blog - need I say anything more? - and I always found it just what I needed to stay up to date with the daily news from the .NET world. 

Driven by Sonu Kapoor and powered by CommunityServer, DNS provides a vast range of services, like forums, newsgroups, web services, a blogging platform and lately even articles written by well known authors explicitly for DotNetSlackers.

Some days ago Sonu announced that DNS is going to pay article's authors as much as $100 per article, and if you've got something to say about .NET and want to write about it I highly encourage you to look at the submission guidelines and submit your article proposals! As I already did ;)
 

kick it on DotNetKicks.com

Vista - a quote from Bellware

Scott Bellware:

That you didn't have sounds at first and believed that this is a reasonable state of affairs attests to how deeply Microsoft has hypnotized the market into believing that software that doesn't just work by default is reasonable.

ASP.NET Singleton-per-Page pattern

A while ago I blogged about a pattern useful to ensure that just a single instance of a class was created and used during a unique request-response pair. That seemed to make sense, since using the HttpContext.Items property prevents a single pipeline from instantiating that class more than once.

At the time I didn't realize that actually one could need a little more granularity and may incur in some issues when that instance needs logically to be bound to a single page instead of a single request-response. One might be wondering where's the difference, since usually during a single request just a single page is executed. That's true most of the times unless you use a subtle method of the HttpServerUtility class called Transfer.

When that method is called, usually via the Server property of the Page class, the execution of the current page is interrupted and the control is passed to the new page specified as input parameter, which executes its whole life cycle from the beginning.

In this case both the pages share the same HttpContext, and if in the singleton-per-request instance of the class you got a reference to the currently executing page (that's what I needed to do in the HeadScriptManager), when you transfer the control to the new page your singleton instance still keeps a reference to the old page.

This seems enough to introduce a sub pattern of the singleton-per-request which might be called singleton-per-page. The only problem is to find a place where to store information which is exclusive to a single page and not shared between pages, even if they are executed in the scope of the same context. 

The Page class features a property called Items, an instance of the HybridDictionary class, and that's where we'll store the singleton instance. Here's a sample code to implement the Singleton-per-Page pattern:

public class SingletonPerPage
{
    public static SingletonPerPage Current
    {
        get
        {
            Page currentPage = HttpContext.Current.Handler as Page;      

            if(currentPage == null)
                throw new NullReferenceException("The page is null");

            return (currentPage.Items["SingletonPerPage"] ??
                   (currentPage.Items["SingletonPerPage"] = 
                    new SingletonPerPage())) as SingletonPerPage;
        }
    }
}

From a mere performance point of view this seems a slightly better solution compared to the singleton-per-request, since the Items properties of the HttpContext and Page classes make use of different bags for storing data. As I said, the Page class uses HybridDictionary, a dictionary which internally makes use of the lightweight ListDictionary class until the number of items stored reaches 9, when it switches over to a HashTable; HttpContext instead makes directly use of a HashTable. What's essential here is to be aware of the scope of the stuff you place there.

kick it on DotNetKicks.com

This site

Search

Go

This Blog

News

Syndication

Sponsors

  • MaximumASP
  • Social Bookmarking
    Online Shopping
    asp.net hosting
    UK online local dating