DB中重复用户名的自定义验证

时间:2010-12-05 05:23:22

标签: asp.net-mvc asp.net-mvc-3 ninject

如果您有更好的方法来处理自定义验证,请告诉我们。我不想要服务层。

请阅读以下第五个选项。

我有

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;
}

在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;
}

从存储库创建方法

public void Create(User user)
{
    user.EnsureValid(); --> Go to User object and do validation
    //Add object to DB
}

5 - 我想要的是什么:

这里我想要DI,以便我可以在User对象上调用第一个IsUserRegistered接口方法 以下IsUserRegistered现在无法正常工作。我需要一种方法来使用界面

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);
    }
}

1 个答案:

答案 0 :(得分:2)

编写您自己的验证属性并将其添加到用户名。

http://www.planetgeek.ch/2010/11/13/official-ninject-mvc-extension-gets-support-for-mvc3/。它解释了如何将依赖项注入验证器。

另请参阅Ninject MVC扩展附带的示例应用程序,它具有一个具有依赖关系的验证器示例。 https://github.com/ninject/ninject.web.mvc