开发者

HttpContext like Object

I like how HTTPContext.Current works. Is there any way that I can implement a similar object that has no relations to HTT开发者_高级运维PContextBase? 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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜