0

I like how HTTPContext.Current works. Is there any way that I can implement a similar object that has no relations to HTTPContextBase? Basically, I would like to create a UserContext. Then in the DAL, I could simple query this UserContext for user-specific information. This object would have to be thread-safe and work in both an ASP.NET environment (so THREAD STATIC attribute won't work) and console/library environments.

5
  • 1
    Why won't [ThreadStatic] work? Commented Jan 13, 2011 at 0:35
  • ThreadStatic won't work because if it is in an ASP.NET enviroment, thread switching can occur. Commented Jan 13, 2011 at 1:24
  • In ASP.NET the worker-thread that you are currently on, can also be used for another requests. "In ASP.NET your code is run on a WorkerThread from the 25 or so threads in the default ASP.NET worker thread pool and the variable that you think is "personal private to your thread" is personal private...to you and every other request that this worker thread has been with." Commented Jan 14, 2011 at 1:26
  • You can just clear the field when the request finishes. Commented Jan 14, 2011 at 15:50
  • piers7.blogspot.com/2005/11/… should clear up why using [ThreadStatic] is bad in ASP.NET Commented Jan 14, 2011 at 17:25

1 Answer 1

2

HttpContext.Current is a Singleton. Thread safe implementation is like this:

using System; public sealed class Singleton { private static volatile Singleton instance; private static object syncRoot = new Object(); private Singleton() {} public static Singleton Current { get { if (instance == null) { lock (syncRoot) { if (instance == null) instance = new Singleton(); } } return instance; } } } 

However using Singleton pattern is not good idea. It is almost "anti-pattern". This obstructs unit testing. Instead of this better to use Dependency Injection Container. http://en.wikipedia.org/wiki/Dependency_injection

Sign up to request clarification or add additional context in comments.

3 Comments

great answer. I wanted to post something along these lines, but couldn't quite figure out how I was going to word it.
this won't work since the singleton is globally available to all running threads. Say this singleton was used in a ASP.NET environment, all requests would have the same instance of the singleton.
You could also use a standard class, and your IOC container could give you a singleton instance of it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.