Custom Validation for Duplicate UserName in DB
If you have better approach to handle custom Validation please let me know. I don't want service layer for this please.
Read below 5th option what I want.
I have
1 - IUserRepository -> bool IsUserRegistered(string userName);
2 - UserRepository with Method
readonly EFDBContainer _db = new EFDBContainer();
public bool IsUserRegistered(string userName)
{
return _db.Users.Any(d => d.UserName == userName);
}
3 - Ninject --> UserController is DI
public 开发者_Python百科static void RegisterServices(IKernel kernel)
{
kernel.Bind<IUserRepository>().To<UserRepositary>();
}
4 - UserController
private readonly IUserRepository _repository;
public ProfileController(IUserRepository repository)
{
_repository = repository;
}
Create Method on Controller
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;
}
Create Method from Repository
public void Create(User user)
{
user.EnsureValid(); --> Go to User object and do validation
//Add object to DB
}
5 - What I want:
Here I want DI so that I can call 1st IsUserRegistered interface method on User object IsUserRegistered below is not working right now. I need a way to use the Interface
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);
}
}
Write your own validation attribute and add it to the user name.
See http://www.planetgeek.ch/2010/11/13/official-ninject-mvc-extension-gets-support-for-mvc3/. It explains how to inject dependencies into validators.
See also the sample application that comes with the Ninject MVC extension it has an example of a validator that has a dependency. https://github.com/ninject/ninject.web.mvc
精彩评论