【发布时间】:2011-02-23 21:35:32
【问题描述】:
我想知道是否有更好的方法来解决这个问题。目标是重用代码。
假设我有一个 Linq-To-SQL 数据上下文,并且我编写了一个“存储库样式”类,它封装了许多我需要的方法并公开了 IQueryables。 (到目前为止,没问题)。
现在,我正在构建一个位于此存储库之上的服务层,许多服务方法将是 11 与存储库方法,但有些不会。我认为代码示例比文字更能说明这一点。
public class ServiceLayer
{
MyClassDataContext context;
IMyRepository rpo;
public ServiceLayer(MyClassDataContext ctx)
{
context = ctx;
rpo = new MyRepository(context);
}
private IQueryable<MyClass> ReadAllMyClass()
{
// pretend there is some complex business logic here
// and maybe some filtering of the current users access to "all"
// that I don't want to repeat in all of the public methods that access
// MyClass objects.
return rpo.ReadAllMyClass();
}
public IEnumerable<MyClass> GetAllMyClass()
{
// call private IQueryable so we can do attional "in-database" processing
return this.ReadAllMyClass();
}
public IEnumerable<MyClass> GetActiveMyClass()
{
// call private IQueryable so we can do attional "in-database" processing
// in this case a .Where() clause
return this.ReadAllMyClass().Where(mc => mc.IsActive.Equals(true));
}
#region "Something my class MAY need to do in the future"
private IQueryable<MyOtherTable> ReadAllMyOtherTable()
{
// there could be additional constrains which define
// "all" for the current user
return context.MyOtherTable;
}
public IEnumerable<MyOtherTable> GetAllMyOtherTable()
{
return this.ReadAllMyOtherTable();
}
public IEnumerable<MyOtherTable> GetInactiveOtherTable()
{
return this.ReadAllMyOtherTable.Where(ot => ot.IsActive.Equals(false));
}
#endregion
}
这种特殊情况并不是最好的说明,因为我可以直接在 GetActiveMyClass 方法中调用存储库,但我们假设我的私有 IQueryable 做了一些我不想在两者中复制的额外处理和业务逻辑我的公共方法。
这是解决此类问题的坏方法吗?我不认为它如此复杂以至于确实需要在存储库和服务类之间构建第三个类,但我想听听你的想法。
为了争论,我们假设另外两件事。
- 此服务将通过 WCF 公开,并且这些公共 IEnumerable 方法中的每一个都将在每个返回的集合上调用
.Select(m => m.ToViewModel()),这会将其转换为 POCO 以进行序列化。 - 服务最终需要公开一些
context.SomeOtherTable,它们不会被包装到存储库中。
【问题讨论】: