0
如果您有更好的方法來處理自定義驗證請讓我知道。請不要爲此服務層。DB中重複用戶名的自定義驗證
閱讀下面第5個選項我想要的。
我有
1 - IUserRepository -> bool IsUserRegistered(string userName);
2 - UserRepository用方法
readonly EFDBContainer _db = new EFDBContainer();
public bool IsUserRegistered(string userName)
{
return _db.Users.Any(d => d.UserName == userName);
}
3 - Ninject - > UserController的是DI
public static void RegisterServices(IKernel kernel)
{
kernel.Bind<IUserRepository>().To<UserRepositary>();
}
4 - UserController中
private readonly IUserRepository _repository;
public ProfileController(IUserRepository repository)
{
_repository = repository;
}
控制器上創建方法
HttpPost]
public ActionResult Create(string confirmButton, User user)
{
if (ModelState.IsValid)
{
try
{
_repository.Create(user); --> This calling Create Method below before this EnsureValid is Called
return //Do Redirection
}
catch (RuleViolationException)
{
this.UpdateModelStateWithViolations(user, ViewData.ModelState);
}
}
return //to View;
}
從庫中創建方法
public void Create(User user)
{
user.EnsureValid(); --> Go to User object and do validation
//Add object to DB
}
5 - 我想要什麼:
在這裏,我想DI讓我能在User obj上調用第一個IsUserRegistered接口方法ect IsUserRegistered below目前無法正常工作。我需要一種方法來使用接口
public partial class User: IRuleEntity
{
public List<RuleViolation> GetRuleViolations()
{
List<RuleViolation> validationIssues = new List<RuleViolation>();
if (IsUserRegistered(userName))
validationIssues.Add(new RuleViolation("UserName", UserName, "Username already exists. Please enter a different user name."));
return validationIssues;
}
public void EnsureValid()
{
List<RuleViolation> issues = GetRuleViolations();
if (issues.Count != 0)
throw new RuleViolationException("Business Rule Violations", issues);
}
}