开发者

Validate interface using IoC

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜