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


上一篇:《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權限申請沒有被批准,並且申請已被鎖定,具體請聯系contact@cnblogs.com。";
            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 領域模型會更加健壯。

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM