Bigeyes
Bigeyes

Reputation: 1666

Pass value to the custom attribute

I want to customize a attribute. Say

public class IdExistAttribute : ValidationAttribute
{

    protected override ValidationResult IsValid(object value,
                                                  ValidationContext validationContext)
    {
        string id= value.ToString();
        if(ListOfId.Contains(id))
        {
           return new ValidationResult("Id is already existing");
        }

        return ValidationResult.Success;
     }
 }

The question is that ListOfId is from service, I can't consume the service inside the attribute. So how to pass it from outside?

I want to use the attribute as

private string _id;
[IdExist]
public string Id
{
  get{return _id;}
  set{_id=value;}
}

Upvotes: 4

Views: 616

Answers (1)

ProgrammingLlama
ProgrammingLlama

Reputation: 38767

ValidationContext provide access to the registered dependency injection container via GetService.

Quoting Andrew Lock:

As you can see, you are provided a ValidationContext as part of the method call. The context object contains a number of properties related to the object currently being validated, and also this handy number:

public object GetService(Type serviceType);

So you can use ValidationContext like so:

protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
    var service = (IExternalService) validationContext
                         .GetService(typeof(IExternalService));
    // use service
}

Upvotes: 1

Related Questions