问题
I have a custom attribute in asp.net mvc and use structure map. how can I inject ContextDB into the custom ValidationAttribute?
[AttributeUsage(AttributeTargets.Property)]
public class CustomValidationAttribute : ValidationAttribute
{
public ContextDB _Context { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
Settings settings = new Settings(_Context);
// Checking...
return ValidationResult.Success;
}
}
my code doesn't work, _Context is null. what should I do?
Thanks.
回答1:
If you have registered your DI to MVC you could use MVC's dependency resolver everywhere.
public class CustomValidationAttribute : ValidationAttribute
{
private ContextDB _context { get; set; }
public CustomValidationAttribute()
{
// assuming you have a IContextDB interface which mapped to
// ContextDB in your StructureMap
_context =DependencyResolver.Current.GetService<IContextDB>();
}
// rest of your code
}
For more advanced scenario look at Setter Injection concept also.
来源:https://stackoverflow.com/questions/31895880/asp-net-mvc-custom-validation-attribute-with-structuremap