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?