DDD 領域驅動設計-領域模型中的用戶設計

来源:http://www.cnblogs.com/xishuai/archive/2016/04/27/domain-model-with-user-design.html
-Advertisement-
Play Games

上一篇:《 "DDD 領域驅動設計-如何控制業務流程?" 》 開源地址: "https://github.com/yuezhongxin/CNBlogs.Apply.Sample" (代碼已更新,並增加了應用層代碼) 在 JsPermissionApply 領域模型中,User 被設計為值對象,也就 ...


上一篇:《DDD 領域驅動設計-如何控制業務流程?

開源地址:https://github.com/yuezhongxin/CNBlogs.Apply.Sample(代碼已更新,並增加了應用層代碼)

在 JsPermissionApply 領域模型中,User 被設計為值對象,也就是 JsPermissionApply 實體中的 UserId 屬性,這個沒啥問題,但後來再實現代碼的時候,就出現了一些問題,在 JS 許可權申請和審核系統中,用戶的一些操作如下:

  1. 申請:根據當前 LoginName 獲取 UserId,UserId 存儲在 JsPermissionApply 實體。
  2. 驗證:根據 UserId 判斷此用戶是否擁有博客。
  3. 許可權:根據當前 LoginName,判斷此用戶是否擁有審核許可權。
  4. 審核:迴圈遍歷每個申請,根據其 UserId 獲取其他的用戶信息。

對於上面的四個用戶操作,因為每個請求都會耗費時間,所以我們需要儘量簡化其操作,尤其是第四個操作,如果管理員要審核 10 個申請,那麼就得請求用戶服務 10 次,那怎麼省掉這個操作呢?就是用戶在申請 JS 許可權的時候,我們先獲取用戶信息,然後存在 JsPermissionApply 實體中,如何這樣設計,那麼第二個用戶驗證操作,也可以省掉。

代碼如何實現?我之前想在 JsPermissionApply 實體中,直接增加如下值對象:

public int UserId { get; set; }

public string UserLoginName { get; set; }

public string UserDisplayName { get; set; }

public string UserEmail { get; set; }

public string UserAlias { get; set; }

這樣實現也沒什麼問題,但 JsPermissionApply 實體的構造函數參數賦值,就變的很麻煩,UserId 標識一個 User,那一個 User 也是標識一個 User,所以我們可以直接把 User 設計為值對象,示例代碼:

namespace CNBlogs.Apply.Domain.ValueObjects
{
    public class User
    {
        public string LoginName { get; set; }

        public string DisplayName { get; set; }

        public string Email { get; set; }

        public string Alias { get; set; }

        [JsonProperty("SpaceUserID")]
        public int Id { get; set; }
    }
}

JsonProperty 的作用是在 UserService 獲取用戶信息的時候,映射源屬性名稱,GetUserByLoginName 示例代碼:

namespace CNBlogs.Apply.ServiceAgent
{
    public class UserService
    {
        private static string userHost = "";

        public static async Task<User> GetUserByLoginName(string loginName)
        {
            using (var httpCilent = new HttpClient())
            {
                httpCilent.BaseAddress = new System.Uri(userHost);
                var response = await httpCilent.GetAsync($"/users?loginName={Uri.EscapeDataString(loginName)}");
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return await response.Content.ReadAsAsync<CNBlogs.Apply.Domain.ValueObjects.User>();
                }
                return null;
            }
        }
    }
}

JsPermissionApply 實體代碼:

namespace CNBlogs.Apply.Domain
{
    public class JsPermissionApply : IAggregateRoot
    {
        private IEventBus eventBus;

        public JsPermissionApply()
        { }

        public JsPermissionApply(string reason, User user, string ip)
        {
            if (string.IsNullOrEmpty(reason))
            {
                throw new ArgumentException("申請內容不能為空");
            }
            if (reason.Length > 3000)
            {
                throw new ArgumentException("申請內容超出最大長度");
            }
            if (user == null)
            {
                throw new ArgumentException("用戶為null");
            }
            if (user.Id == 0)
            {
                throw new ArgumentException("用戶Id為0");
            }
            this.Reason = HttpUtility.HtmlEncode(reason);
            this.User = user;
            this.Ip = ip;
            this.Status = Status.Wait;
        }

        public int Id { get; private set; }

        public string Reason { get; private set; }

        public virtual User User { get; private set; }

        public Status Status { get; private set; } = Status.Wait;

        public string Ip { get; private set; }

        public DateTime ApplyTime { get; private set; } = DateTime.Now;

        public string ReplyContent { get; private set; }

        public DateTime? ApprovedTime { get; private set; }

        public bool IsActive { get; private set; } = true;

        public async Task<bool> Pass()
        {
            if (this.Status != Status.Wait)
            {
                return false;
            }
            this.Status = Status.Pass;
            this.ApprovedTime = DateTime.Now;
            this.ReplyContent = "恭喜您!您的JS許可權申請已通過審批。";
            eventBus = IocContainer.Default.Resolve<IEventBus>();
            await eventBus.Publish(new JsPermissionOpenedEvent() { UserId = this.User.Id });
            return true;
        }

        public bool Deny(string replyContent)
        {
            if (this.Status != Status.Wait)
            {
                return false;
            }
            this.Status = Status.Deny;
            this.ApprovedTime = DateTime.Now;
            this.ReplyContent = replyContent;
            return true;
        }

        public bool Lock()
        {
            if (this.Status != Status.Wait)
            {
                return false;
            }
            this.Status = Status.Lock;
            this.ApprovedTime = DateTime.Now;
            this.ReplyContent = "抱歉!您的JS許可權申請沒有被批准,並且申請已被鎖定,具體請聯繫[email protected]。";
            return true;
        }

        public async Task Passed()
        {
            if (this.Status != Status.Pass)
            {
                return;
            }
            eventBus = IocContainer.Default.Resolve<IEventBus>();
            await eventBus.Publish(new MessageSentEvent() { Title = "您的JS許可權申請已批准", Content = this.ReplyContent, RecipientId = this.User.Id });
        }

        public async Task Denied()
        {
            if (this.Status != Status.Deny)
            {
                return;
            }
            eventBus = IocContainer.Default.Resolve<IEventBus>();
            await eventBus.Publish(new MessageSentEvent() { Title = "您的JS許可權申請未通過審批", Content = this.ReplyContent, RecipientId = this.User.Id });
        }

        public async Task Locked()
        {
            if (this.Status != Status.Lock)
            {
                return;
            }
            eventBus = IocContainer.Default.Resolve<IEventBus>();
            await eventBus.Publish(new MessageSentEvent() { Title = "您的JS許可權申請未通過審批", Content = this.ReplyContent, RecipientId = this.User.Id });
        }
    }
}

JsPermissionApply 實體去除了 UserId 屬性,並增加了 User 值對象,構造函數也相應進行了更新,如果實體進行這樣設計,那資料庫存儲該如何設計呢?EF 不需要添加任何的映射代碼,直接用 EF Migration 應用更新就可以了,生成 JsPermissionApplys 表結構:

SELECT TOP 1000 [Id]
      ,[Reason]
      ,[Status]
      ,[Ip]
      ,[ApplyTime]
      ,[ReplyContent]
      ,[ApprovedTime]
      ,[IsActive]
      ,[User_LoginName]
      ,[User_DisplayName]
      ,[User_Email]
      ,[User_Alias]
      ,[User_Id]
  FROM [cnblogs_apply].[dbo].[JsPermissionApplys]

JsPermissionApplyDTO 示例代碼:

namespace CNBlogs.Apply.Application.DTOs
{
    public class JsPermissionApplyDTO
    {
        public int Id { get; set; }

        public string Reason { get; set; }

        public string Ip { get; set; }

        public DateTime ApplyTime { get; set; }

        public int UserId { get; set; }

        public string UserLoginName { get; set; }

        public string UserDisplayName { get; set; }

        public string UserEmail { get; set; }

        public string UserAlias { get; set; }
    }
}

使用.ProjectTo<JsPermissionApplyDTO>().ToListAsync()獲取申請列表的時候,AutoMapper 也不需要添加任何對 JsPermissionApply 和 JsPermissionApplyDTO 的映射代碼。

另外領域服務、應用服務和單元測試代碼,也對應進行了更新,詳細查看上面的開源地址。

UserId 換為 User 設計,大致有兩個好處:

  • 用戶信息在申請的時候獲取並存儲,審核直接展示,減少不必要的請求開銷。
  • 有利於 User 的擴展,JsPermissionApply 領域模型會更加健壯。

技術是設計的實現,不能用技術來影響設計。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • package com.travelsky.test;import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnectio ...
  • <?php /** *製作驗證碼 *1.啟動session *2.設定標頭 *3.創建畫布 *4.創建顏色 *5.創建隨機數並放到畫布上 *6.將得到的若幹隨機數放入session中 *7.添加干擾點或干擾線 *8.輸出畫布 *9.銷毀畫布資源 */ //1.啟動session session_st ...
  • 具體應用場景是,當subject的某個動作需要引發一系列不同對象的動作(比如你是一個班長要去通知班裡的某些人),與其一個一個的手動調用觸發的方法(私下裡一個一個通知),不如維護一個列表(建一個群),這個列表存有你想要調用的對象方法(想要通知的人);之後每次做的觸發的時候只要輪詢這個列表就好了(群發) ...
  • Delphi 開發 ERP ...
  • Java中可以使用HttpURLConnection來請求WEB資源。HttpURLConnection對象不能直接構造,需要通過URL.openConnection()來獲得HttpURLConnection對象,示例代碼如下:String szUrl = "http://www.ee2ee.co ...
  • Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. For example, given n = 12, ...
  • 核心技術:Maven,Springmvc mybatis shiro, Druid, Restful, Dubbo, ZooKeeper,Redis,FastDFS,ActiveMQ,Nginx 1. 項目核心代碼結構截圖 項目模塊依賴 特別提醒:開發人員在開發的時候可以將自己的業務REST服務化或 ...
  • ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...