简短回答:
您主要在服务层中使用规范,所以就在那里。
长答案:首先,这里有两个问题:
您的规格应该放在哪里?它们应该在哪里更新?
就像您的存储库接口一样,您的规范应该存在于域层中,因为它们毕竟是特定于域的。有一个关于SO的问题 https://stackoverflow.com/questions/7164034/ddd-and-implementing-persistence在存储库接口上讨论了这个问题。
但他们应该在哪里更新呢?嗯,我用Linq规格 http://linqspecs.codeplex.com/releases/view/46498在我的存储库上,并且我的存储库上大多有三种方法:
public interface ILinqSpecsRepository<T>
{
IEnumerable<T> FindAll(Specification<T> specification);
IEnumerable<T> FindAll<TRelated>(Specification<T> specification, Expression<Func<T, TRelated>> fetchExpression);
T FindOne(Specification<T> specification);
}
我的其余查询是在我的服务层中构建的。这可以防止存储库因 GetUserByEmail、GetUserById、GetUserByStatus 等方法而变得臃肿。
在我的服务中,我更新了我的规范并将它们传递给我的存储库的 FindAll 或 FindOne 方法。例如:
public User GetUserByEmail(string email)
{
var withEmail = new UserByEmail(email); // the specification
return userRepository.FindOne(withEmail);
}
这是规格:
public class UserByEmail : Specification<User>
{
private readonly string email;
public UserByEmail(string email)
{
this.email = email;
}
#region Overrides of Specification<User>
public override Expression<Func<User, bool>> IsSatisfiedBy()
{
return x => x.Email == email;
}
#endregion
}
因此,为了回答您的问题,服务层中的规格是新的(在我的书中)。
我觉得唯一应该注入到模型类中的东西
是“服务”
IMO 你不应该向域实体中注入任何东西。
除此之外,相关规范需要一个存储库
以确定是否“满意”。
那是一个代码气味 http://www.codinghorror.com/blog/2006/05/code-smells.html。我会在那里审查你的代码。规范绝对不需要存储库。