我有一个定制的ValidationAttribute,它检查另一个用户是否已经存在。为此,它需要对我的数据访问层的访问,这是一个由Unity注入到我的控制器中的实例
如何将此参数(或任何相关内容)作为参数传递到我的自定义验证程序中?
这个是可能的吗?在我创造达尔的地方,那应该是个参数
public class EmailIsUnique : ValidationAttribute
{
private string _errorMessage = "An account with this {0} already exists";
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DataAccessHelper Dal = new DataAccessHelper(SharedResolver.AppSettingsHelper().DbConnectionString); //todo, this is way too slow
bool isValid = true;
if(value == null) {
isValid = false;
_errorMessage = "{0} Cannot be empty";
} else {
string email = value.ToString();
if (Dal.User.FindByEmail(email) != null)
{
isValid = false;
}
}
if (isValid)
return ValidationResult.Success;
else
return new ValidationResult(String.Format(_errorMessage, validationContext.DisplayName));
}
}发布于 2013-12-24 09:14:34
我不太确定您是否能够将运行时参数传递到属性中。
您可以使用DependencyResolver.Current.GetService<DataAccessHelper>()解决您的DataAccessHelper(考虑到您已经注册了DataAccessHelper)。
你可能更有可能把DataAccessHelper注册为IDataAccessHelper之类的?在这种情况下,您可以调用GetService<IDataAccessHelper>
public class EmailIsUnique : ValidationAttribute
{
private string _errorMessage = "An account with this {0} already exists";
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
IDataAccessHelper Dal = DependencyResolver.Current.GetService<IDataAccessHelper>(); // too slow
bool isValid = true;
if(value == null) {
isValid = false;
_errorMessage = "{0} Cannot be empty";
} else {
string email = value.ToString();
if (Dal.User.FindByEmail(email) != null)
{
isValid = false;
}
}
if (isValid)
return ValidationResult.Success;
else
return new ValidationResult(String.Format(_errorMessage, validationContext.DisplayName));
}
}或
public class EmailIsUnique : ValidationAttribute
{
[Dependency]
public IDataAccessHelper DataAccess {get;set;}
private string _errorMessage = "An account with this {0} already exists";
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
bool isValid = true;
if(value == null)
{
isValid = false;
_errorMessage = "{0} Cannot be empty";
}
else
{
string email = value.ToString();
if (DataAccess.User.FindByEmail(email) != null)
{
isValid = false;
}
}
if (isValid)
return ValidationResult.Success;
else
return new ValidationResult(String.Format(_errorMessage, validationContext.DisplayName));
}
}发布于 2013-12-24 09:07:15
您可能正在寻找属性注入。看看this的帖子。第一个解决方案是创建支持依赖注入的自定义筛选器提供程序。
第二个解决方案是使用Service模式并在属性构造函数中获取您服务的实例。
发布于 2013-12-24 08:50:29
yes.you可以传递在模型类中使用的参数,如下所示:
[EmailIsUnique()]
public string Email {get; set;}因此,这将自动传递电子邮件作为参数,并检查该值。
https://stackoverflow.com/questions/20757615
复制相似问题