Asp.Net MVC Custom Validation Attribute With StructureMap

我是研究僧i 提交于 2019-12-08 02:16:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!