C# 将值传递给自定义属性
我想自定义一个属性。说C# 将值传递给自定义属性,c#,attributes,C#,Attributes,我想自定义一个属性。说 public class IdExistAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { string id= value.ToS
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;
}
}
问题是ListOfId
来自服务,我不能使用属性中的服务。那么如何从外部传递呢
我想将该属性用作
private string _id;
[IdExist]
public string Id
{
get{return _id;}
set{_id=value;}
}
通过GetService
提供对已注册依赖项注入容器的访问
引述:
如您所见,作为方法调用的一部分,提供了一个ValidationContext。上下文对象包含许多与当前正在验证的对象相关的属性,以及这个方便的数字:
公共对象GetService(类型serviceType)
因此,您可以像这样使用ValidationContext
:
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var service = (IExternalService) validationContext
.GetService(typeof(IExternalService));
// use service
}
我们可以将列表值传递给属性吗?因为我可以在模型类中获得值。不幸的是,我没有类似于
IExternalService
的东西,您只能将编译时值传递到属性[declaration]中。唯一的其他选项是在IdExistAttribute
上使用static
值,然后在使用属性之前设置该值。如果可能的话,我建议为此创建一个服务。缺点是如果属性更改,我必须调用该服务以再次获得相同的值。它有性能问题。也许我不应该使用属性?也许还有其他验证方法?请参见