當服務層僅執行任務(檢查Id是否存在,發送電子郵件等)時,讓控制器知道是否存在的最佳方式是什麼任何錯誤?使服務與控制器溝通錯誤的最佳方式
兩個解決方案,我能想到的:
一個額外的「破規矩」參數總是通過引用傳遞到服務層的方法,其中如果有任何錯誤,將更新。
讓服務引發異常並讓控制器執行try/catch。
推薦這兩種方法嗎?如果沒有,我可以採取什麼方法讓服務層讓控制器知道哪裏出了問題(如無效參數)?
當服務層僅執行任務(檢查Id是否存在,發送電子郵件等)時,讓控制器知道是否存在的最佳方式是什麼任何錯誤?使服務與控制器溝通錯誤的最佳方式
兩個解決方案,我能想到的:
一個額外的「破規矩」參數總是通過引用傳遞到服務層的方法,其中如果有任何錯誤,將更新。
讓服務引發異常並讓控制器執行try/catch。
推薦這兩種方法嗎?如果沒有,我可以採取什麼方法讓服務層讓控制器知道哪裏出了問題(如無效參數)?
你的服務應該收集所有破碎的規則,然後拋出「BrokenRuleException」。您的控制器將捕獲「BrokenRuleException」,然後使用斷點來更新用戶界面。
我創建的接口:
public interface IModelStateWrapper
{
void AddModelError(string name, string error);
}
然後,我創建了每個控制器的實現:
public class ControllerModelStateWrapper : IModelStateWrapper
{
private ModelStateDictionary _dictionary;
public ControllerModelStateWrapper(ModelStateDictionary dictionary)
{
_dictionary = dictionary;
}
public void AddModelError(string name, string error)
{
if (_dictionary[name] == null)
_dictionary.Add(name, new ModelState());
_dictionary[name].Errors.Add(error);
}
}
每個服務實現:
public interface IModelWrapperService
{
IModelStateWrapper ModelWrapper {get;set;}
}
然後我將它設置在控制器:
public UserController(IUserService service)
{
_service.ModelWrapper = new ControllerModelStateWrapper(ModelState);
}
IModelStateWrapper不是最好的名稱,因爲此接口不僅可以與Controller.ModelState一起工作。作品很好。您可以輕鬆地用服務測試中的模擬或其他實現來替換IModelStateWrapper。該解決方案也會自動將ModelState設置爲無效。
我認爲拋出BrokenRuleException是一個不錯的選擇。我個人不喜歡把狀態放在一個服務中,它通常是一個單例(由DI容器執行),並且只有其他單例協作者(在我的情況下是域對象)。