0

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:

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

Now how should I pass the IApplicationDbContext to the attribute in ViewModel class?

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

Generally, is that a good idea to use DI in the case? Maybe there are some other ways?

Slip
  • 593
  • 1
  • 7
  • 21
  • Yes. EF7 with all default settings – Slip Nov 16 '15 at 08:07
  • 2
    You [should not inject any dependencies into attributes](https://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=98). Attributes should be [passive](http://blog.ploeh.dk/2014/06/13/passive-attributes/). – Steven Nov 16 '15 at 08:22

1 Answers1

0

Since you are using EF7, you can use data annotation to ensure unicity of email.

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

You can find more information here

Community
  • 1
  • 1
Bilel Chaouadi
  • 903
  • 1
  • 10
  • 28