在程序中我习惯让所有的*.aspx.cs文件继承自我定义的BasePage类,将一些公共的方法或内容得到有效的复用:

namespace YourWebsite.UIControls
{
    public class BasePage:System.Web.UI.Page
    {

    //write your own properties or method here.

    }
}

例如你可以把Service层的实例声明放到这里:

namespace ISS.SiemensSH.SurveyOL.Website.UIControls
{
    public class BasePage:System.Web.UI.Page
    {

    private UserService _UserService;
    public UserService UserServiceInstance
    {
      get
      {         if(this._UserService == null)         {           this._UserService = new UserService();         }         return this._UserService;       }     } } }

不过这样会存在一个问题,就是当您同样定义了一个BaseUserControl类,您需要重复定义上面代码中的CurrentUserSerivce,形如:

namespace YourWebsite.UIControls
{
    public class BaseUserControl:System.Web.UI.UserControl
    {

    private UserService _UserService;
    public UserService UserServiceInstance
    {
      get
      {
        if(this._UserService == null)
        {
          this._UserService = new UserService();
        }  
        return this._UserService;
      }
    }
    }
}

还是那句话,重复不是好事情。怎么办呢?于是我引入了一个MyContext类,将Service的实例化工作交给MyContext类完成,然后在BasePage,和BaseUserControl中引入MyContext作为属性即可:

public class MyContext
{
        #region Constructor

        private static MyContext _myContext;private MyContext(){}

        public static MyContext GetInstance()
        {
            if (_myContext == null)
            {
                lock (typeof(MyContext))
                {
                    _myContext = new MyContext();
                }

            }
            return _myContext;
        }

        #endregion

        #region Services

        private UserService _UserService;

        /// <summary>
        /// UserService
        /// </summary>
        public UserService UserServiceInstance
        {
            get { return _UserService?? (_UserService= new UserService()); }
        }
        #endregion
}

然后修改BasePage为:

namespace YourWebsite.UIControls
{
    public class BasePage:System.Web.UI.Page
    {
        public Core.MyContext MyContext
        {
            get
            {
                return Core.MyContext.GetInstance();
            }
        }
    }
    public class BaseUserControl:System.Web.UI.UserControl
    {
        public Core.MyContext MyContext
        {
            get
            {
                return Core.MyContext.GetInstance();
            }
        }
    }

}

在具体的页面中这样使用就可以了:

    public partial class Login : BasePage
    {

        protected void Page_Load(object sender, EventArgs e)
        {

      var user = this.MyContext.UserServiceInstance.GetByID("110");    
      //your logic code goes here...
        }
    }

完毕。

 posted on 2012-11-15 09:58  段子手6哥  阅读(512)  评论(0编辑  收藏  举报