【发布时间】:2009-05-15 22:02:28
【问题描述】:
我一直在研究 NerdDinner 教程,其中大部分内容都很有意义。我不确定的是为什么直接在控制器中使用存储库而不是模型对象。例如,如果我们想实现自己的会员系统,并且它有一个带有 Login 方法的 AccountController,那么连接它的最佳解决方案是什么?例如
Login(username,password){
repo = AccountRepository
account = repo.getLogin(username,password)
//check account isn't locked
//check account has been verified etc etc
//throw error or proceed to secure area
}
或
Login(username,password){
repo = AccountRepository
account = repo.getLogin(username,password)
account.login() //business logic is handled in Account (Model)
}
或
Login(username,password){
//no reference to repository
account = Account
//Account (Model) uses repository and handles business logic
account.login(username,password)
}
我建议让 Account 对象直接使用 AccountRepository,而不是 AccountController 从 AccountRepository 获取信息,然后将其传递给 Account 对象,例如
NerdDinnner 风格:
1 个登录请求进来
2 AccountController 使用 AccountRepository 根据请求获取登录详细信息
3 AccountController 使用 Account 对象并从第 1 步传入信息
4 Account对象处理请求并通知AccountController
我的建议:
1 个登录请求进来
2 AccountController根据请求使用Account对象处理登录
3 Account对象使用AccountRepository获取登录详情
4 Account对象处理请求并通知AccountController
后一种风格的原因是,在从 AccountRepository 返回登录详细信息后,将遵循业务规则,例如是否已锁定帐户,是否已验证帐户等 如果使用第一种样式,则获取详细信息然后使用它们的逻辑分为 2 个步骤。后一种风格将所有逻辑保持在一起,同时仍使用 AccountRepository,例如
Account.Login(username,password){
repo = AccountRepository
account = repo.GetLogin(username,password)
//check account isn't locked
//check account has been verified etc etc
//throw error or proceed to secure area
}
我希望这是有道理的。
【问题讨论】:
标签: asp.net-mvc model controller repository-pattern