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.
1 Answer
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
3 Comments
Vadim
great answer. I wanted to post something along these lines, but couldn't quite figure out how I was going to word it.
choudeshell
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.
Rick Rat
You could also use a standard class, and your IOC container could give you a singleton instance of it.
[ThreadStatic]work?