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
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...