如果我理解你的問題,你問到從當前調用其他控制器的操作方法執行操作方法?你通常不會那樣做。 Controller的操作方法的第一條規則是:沒有任何操作方法應該超過10行代碼。基本上,動作方法實際上應該是一種簡單的方法來收集視圖,或在您的域中調用一個動作,然後返回。
換句話說,在SRP模式: http://codebetter.com/karlseguin/2008/12/05/get-solid-single-responsibility-principle/
相反,你將組織你的域邏輯(你的描述考慮域模型的邏輯是什麼,而不是控制器邏輯)此重複的代碼,如在這裏刪除的問題,但是當刪除用戶時也刪除問題等。
// an example of IOC injection of your IUserService
private IUserService
public RegistrationController(IUserService userService)
{
_userService = userService;
}
[HttpPost]
public ActionResult Delete()
{
// insert modelstate and/or validation logic
//
if (User.Identity.IsAuthenticated == false)
{
return RedirectToAction("index", "Home");
}
// good practice to never bubble up exceptions to users
try
{
if (_userService.DeleteByEmail(User.Identity.Name) == false)
{
ModalState.AddModelError(String.Empty, "Not allowed?");
return View();
}
// save it all in a single atomic operation here to keep it all in
// a single Transaction Scope that will rollback properly if there is
// an error.
//
db.SaveChanges();
}
catch (Exception)
{
ModalState.AddModelError(String.Empty, "An error occurred...");
return View();
}
// all ok!
return RedirectToAction("logout");
}
注意這個操作方法是多麼的乾淨。它只需用一行或兩行代碼就可以完成業務,並且可以在很多不同情況下正確處理用戶體驗。現在
,你的域邏輯可以封裝成服務(或供應商,或類似):
namespace MyWebsite.Models
{
public class UserService : IUserService
{
// Todo: convert to some IoC lovin'
//
public Boolean DeleteByEmail(String email)
{
var user =
(from user in db.Registrations
where
user.Email == email
select s).FirstOrDefault();
if (user == null)
return false;
// call into other services to delete them
ProfileDataService.DeleteByUserId(user.UserId);
QuestionsService.DeleteByUserId(user.UserId);
// finally, delete the user
db.Registrations.Delete(user);
// note, I am NOT calling db.SaveChanges() here. Look
// back at the controller method for the atomic operation.
//
return true;
}
}
}
這可以實現不同的方式100S。問題的關鍵是將該邏輯抽象爲一個通用的代碼庫或「域」。我選擇將該邏輯放在您的當前網站命名空間下的Models中作爲此示例中的快捷方式。
至於其他控制器上的其他Delete()
方法,您可以調用QuestionsService.DeleteByUserId()
和ProfileDataService.DeleteByUserId()
來處理這些方法。如上所示,您甚至可以在域中共享這些服務。
噢好的非常非常感謝你我會這樣做,一直試圖弄清楚這一點。謝謝 !! – user1591668
請注意,我允許通過控制器和服務共享DataContext。標準IoC實踐將相同的DataContext實例注入控制器以及被調用的服務。還有很多其他方式,例如UNit of Work模式也可以傳遞到服務中。給他自己。 – eduncan911
我的答案有大約5種不同的模式。大聲笑。對不起,只是多閱讀一下工作單位和/或IOC和SRP以及域名服務等。 – eduncan911