私があなたの質問を理解した場合、現在実行中のアクション メソッドから他のコントローラーのアクション メソッドを呼び出すように求めていますか? 通常、これは行いません。コントローラーのアクション メソッドの最初の規則は、アクション メソッドは 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");
}
このアクション メソッドがいかにクリーンであるかに注目してください。1 行または 2 行のコードと、さまざまな状況でユーザーのエクスペリエンスを適切に処理するための多数の出口パスを使用するだけで、ビジネスに取り掛かることができます。
これで、ドメイン ロジックをサービス (またはプロバイダーなど) にカプセル化できます。
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;
}
}
}
これは、何百もの異なる方法で実装できます。ポイントは、そのロジックを共通のコードベース、つまり「ドメイン」に抽象化することです。この例では、そのロジックをモデルの下の現在の Web サイト名前空間にショートカットとして配置することにしました。
他のコントローラーの他のメソッドについては、それらを処理するために aとをDelete()
呼び出すだけです。上で示したように、これらのサービスをドメイン全体で共有することもできます。QuestionsService.DeleteByUserId()
ProfileDataService.DeleteByUserId()