我正在寻找关于如何构建验证服务层的教程。我希望该图层存在于我的“域”组合中。目前我已经有了我的域模型和(可能不是最好的)通用存储库实现。构建验证服务层
我的仓库实现旁边:
public sealed class Repository<T> : Interface.IRepository<T> where T : Entity<T>
{
private ISessionFactory sessionFactory;
public Repository(ISessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
public T Get(Guid id)
{
using(var session = this.sessionFactory.OpenSession())
{
return session.Get<T>(id);
}
}
public IQueryable<T> Get(Expression<Func<T, Boolean>> predicate)
{
using(var session = this.sessionFactory.OpenSession())
{
return session.Query<T>().Where(predicate);
}
}
public IQueryable<T> All()
{
using(var session = this.sessionFactory.OpenSession())
{
return session.Query<T>();
}
}
public void Add(T entity)
{
// execute validation here?
using(var session = this.sessionFactory.OpenSession())
using(var transaction = session.BeginTransaction())
{
session.Save(entity);
transaction.Commit();
}
}
public void Remove(T entity)
{
using(var session = this.sessionFactory.OpenSession())
using(var transaction = session.BeginTransaction())
{
session.Delete(entity);
transaction.Commit();
}
}
public void Update(T entity)
{
// make changes &
// execute validation here?
using(var session = this.sessionFactory.OpenSession())
using(var transaction = session.BeginTransaction())
{
session.Update(entity);
transaction.Commit();
}
}
}
我想用FluentValidation
验证实体。据我了解,在仓库范围内,只有两个地方需要进行验证:添加和更新实体时。
首先,我认为把IValidator<T>
作为参数传递给基础机构类:
public abstract class Entity<T> where T : Entity<T>
{
// ...
public virtual String ValidationMessage
{
get;
private set;
}
public virtual Boolean Validate(IValidator<T> validator)
{
try
{
validator.ValidateAndThrow(this as T);
return true;
}
catch(ValidationException ex)
{
this.ValidationMessage = ex.Message;
return false;
}
}
// ...
}
但它似乎并不正确。
从设计的角度来看,我该如何做到这一点?任何意见或教程表示赞赏。
谢谢!