在我們的應用程序中,我們有一個場景,我們需要根據業務規則和當前用戶的上下文來驗證屬性更新。我正在嘗試確定進行驗證的最佳方式,因爲我認爲域模型不應該瞭解當前用戶。我們的正常授權與域分開,與此場景不同。上下文域驅動模型驗證
這個驗證應該發生在哪裏,並且有更好的方法來處理它?域模型應該知道用戶?任何幫助或輸入讚賞。
簡單示例: 我們訂購的批准數量。只有特定的用戶類型才能在特定的方向上更新數量。這是在域聚合中驗證的正確方法嗎?
public enum UserType
{
ViewUserType,
RequesterUserType,
SupplierUserType
}
public class Order
{
public int OrderId {get; private set}
public int RequestedQuantity {get; private set}
public int ApprovedQuantity {get; private set}
public void RequestQuantity(int quantity, UserType userType)
{
if (userType == UserType.RequesterUserType)
{
this.RequestedQuantity = quantity;
}
}
// Question: The direction that the approved quantity can change is a business rule
// but directly deals with the context of the user. Should the model know about the user
// or should this validation be pulled out to either the application service, a model extension,
// or maybe a specification?
public void ApproveQuantity(int quantity, UserType userType)
{
if (userType == UserType.RequesterUserType)
{
if (quantity <= this.ApprovedQuantity)
{
// Requester type user can only update if lowering the approved quantity
this.ApprovedQuantity = quantity;
}
}
else if(userType == UserType.SupplierUserType)
{
if (quantity >= this.ApprovedQuantity)
{
// Supplier type user can only update if increasing the approved quantity
this.ApprovedQuantity = quantity;
}
}
}
}
感謝您的反饋伊夫。 'requester.MustBeAbleToApproveQuantity()'方法的意圖是檢查動作是否被允許,並拋出異常或返回一個布爾結果如果不允許該動作? 現在我在應用程序層有訂單服務。服務器使用IOrderAuthorizer來確定用戶所處的角色。然後,我會爲已批准的數量進行更新。 – user2354863 2013-05-07 02:03:57
要增加更多複雜性,如果存在多個狀態:草稿,提交和最終狀態會怎樣。在提交狀態下,請求者可以以任何方式更新批准的數量,但在最終狀態下,它們只能降低它(如簡單示例)。這會改變你解決問題的方式嗎? – user2354863 2013-05-07 02:04:30
MustXXX方法拋出我的例子。 – 2013-05-07 14:34:36