简体   繁体   English

ASP.Net 5 DI +自定义属性构造函数

[英]ASP.Net 5 DI + Custom attribute constructor

I need some extra logic about user's registration. 我需要有关用户注册的一些额外逻辑。 So I wrote the following: 所以我写了以下内容:

public class UniqueEmail : ValidationAttribute
{
    IApplicationDbContext _context;

    public UniqueEmail(IApplicationDbContext context)
    {
        _context = context;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        int count = _context.Users.Where(u => u.Email == value.ToString() && u.EmailConfirmed == true).Count();
        if (count == 0) return ValidationResult.Success;
        return new ValidationResult("unique email needed from attribute");
    }

}

In Startup.cs : Startup.cs

services.AddScoped<IApplicationDbContext>(p => p.GetService<ApplicationDbContext>());

Now how should I pass the IApplicationDbContext to the attribute in ViewModel class? 现在如何将IApplicationDbContext传递给ViewModel类中的属性?

[UniqueEmail(/*?*/)]
public string Email { get; set; }

Generally, is that a good idea to use DI in the case? 通常,在这种情况下使用DI是个好主意吗? Maybe there are some other ways? 也许还有其他方法?

Since you are using EF7, you can use data annotation to ensure unicity of email. 由于使用的是EF7,因此可以使用数据注释来确保电子邮件的唯一性。

[Index("IX_Email", IsUnique = true)]
public string Email{ get; set; }

You can find more information here 您可以在这里找到更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM