在ASP.Net MVC中保持干燥

Joh*_*zen 5 c# asp.net-mvc dry

我目前在我的第一个ASP.Net MVC应用程序大约两个半星期,到目前为止,我喜欢它.

这个当前项目是ASP.Net WebForms项目的一个端口,我正在努力保持功能.一切进展顺利.

但是,我发现自己在重复......我自己.

例如,在我的BaseController类中,在我的BaseViewPage中,在我的BaseViewUserControl中,在我的BaseViewMasterPage中,我有以下代码:

protected LanLordzApplicationManager AppManager
{
    get
    {
        if(Session["Application"] == null)
        {
            Session["Application"] = new LanLordzApplicationManager(Server.MapPath("~/"));
        }

        return (LanLordzApplicationManager)Session["Application"];
    }
}

protected User CurrentUser
{
    get
    {
        if (Session["UserID"] == null && this.Request.Cookies["AutoLogOnKey"] != null && !string.IsNullOrEmpty(this.Request.Cookies["AutoLogOnKey"].Value))
        {
            this.CurrentUser = this.AppManager.RecallUser(this.Request.Cookies["AutoLogOnKey"].Value, Request.UserHostAddress);
        }

        if (Session["UserID"] == null)
        {
            return null;
        }
        else
        {
            return this.AppManager.GetUserByUserID((long)Session["UserID"]);
        }
    }
    set
    {
        Session["UserID"] = value.UserID;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,这不是漂亮的代码.我想稍微解决一下,但截至目前,我正在四处修理它.事实上,它已成为一些错误的来源,这意味着再次将它固定在所有四个地方.

你怎么建议我保持这个系统DRY? 请注意,由于多种原因,这两个对象必须保留在会话中.

Bla*_*lor 4

您可以从 BaseViewPage、BaseViewUserControl 和 BaseViewMasterPage 中删除代码。渲染视图中使用的所有数据都可以作为所有视图中已可用的视图数据从控制器传递给它们。这至少将您的代码集中到控制器基类。