Asp.Net MVC自定义验证属​​性以StructureMap [英] Asp.Net MVC Custom Validation Attribute With StructureMap

查看:150
本文介绍了Asp.Net MVC自定义验证属​​性以StructureMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在asp.net MVC和利用结构图自定义属性。
我怎么能注入ContextDB到自定义ValidationAttribute?

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;
    }
}

我的code不起作用,_Context为空。
我该怎么办?

my code doesn't work, _Context is null. what should I do?

感谢。

推荐答案

如果您已经注册DI到MVC,你可以在任何地方使用MVC的依赖解析器。

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
}

有关更高级的场景看Setter注入概念也。

For more advanced scenario look at Setter Injection concept also.

这篇关于Asp.Net MVC自定义验证属​​性以StructureMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆