单例模式(控制线程内唯一实例化对象)

  创建ObjectContext对象实例,使得在一次请求中保持实例化一个对象。

    方法一:通过HttpContext控制,线程内唯一

      

        /// <summary>
        /// 通过HttpContext,控制一次请求中实例唯一
      /// </summary>
        /// <returns></returns>
        public static Person SingleHttpContext() 
        {
            Person p = HttpContext.Current.Items["person"] as Person;

            if (p == null) 
            {
                p = new Person();
                HttpContext.Current.Items.Add("person",p);
            }

            return p;
        }

 

    方法二:通过线程块控制,线程内唯一

         /// <summary>
        /// 通过线程块,控制线程内实例唯一
      /// </summary>
        /// <returns></returns>
        public static Person SingleCallContext() 
        {
            Person p = CallContext.GetData("person") as Person;

            if (p == null) 
            {
                p = new Person();
                CallContext.SetData("person", p);
            }

            return p;
        }

 

 

posted @ 2013-05-26 21:25  hello*boy  阅读(645)  评论(0编辑  收藏  举报