I have a domain model that uses IoC with Microsoft Unity. For the validation I use VAB and I decorate the interface, not the entity. The code the following:
interface IJob : IValidable
{
[NotNullValidator]
st开发者_如何学编程ring Name { get; set; }
}
interface IValidable
{
bool IsValid { get; }
void ValidationResults Validate();
}
class Job : IJob
{
string Name { get; set; }
public virtual bool IsValid
{
get { try
{
return Validate().IsValid;
}
catch
{
return false;
} }
}
public ValidationResults Validate()
{
return Validation.Validate(this);
}
}
If I decorate directly the class with the VAB attributes, the validation works. If I use the validation only in the interface, it doesn't. This is how we render a new instance:
ioC.RegisterType<IJob, Job>();
IJob job = ioC.Resolve<IJob>();
return job.IsValid;
The code works if the validation attributes are also in the class, otherwise it doesn't. Why?
The correct implementation will be:
ValidationFactory.CreateValidator<IJob>().Validate(job);
In order to do that, my interface IValidable has became IValidable where
interface IJob : IValidable<IJob> { }
In this way I will be able to validate against the interface. So I will recycle this interface to validate also the Dto!
:D
精彩评论