7

我有一个模型类,它是从我的存储库类中的“GetById”方法加载的。我现在需要向这个实体添加额外的属性,这些属性没有保存在数据库中,而是由服务类计算得出的。就像是:

public class MyEntity
{
    public int ThingId { get; set; };
    public string ThingName { get; set; }

    // Set from the service
    public int WooFactor { get; set; }
}

public class WooFactorGenerator
{
    public int CalculateWooFactor(MyEntity thing); // Hits other services and repo's to eventually determine the woo factor.
}

// Code to get a "MyEntity":

var myEntity = repo.GetById(1);
var gen = new WooFactorGenerator();
myEntity.WooFactor = gen.CalculateWooFactor(myEntity);

所以为了加载/饱和一个 MyEntity 对象,我需要从数据库加载,然后调用生成器来确定“woo 因子”(咳咳)。从架构的角度来看,这段代码应该去哪里?目前的想法:

1)在存储库中:如果我在这里添加它,我觉得我将太多的责任交给了 repo。

2) 在“MyEntity”类中。在此处添加代码,可能会在访问 WooFactor 时延迟加载它。这会给 MyEntity 添加很多依赖项。

3)一个单独的服务类 - 似乎矫枉过正且不必要。

4

4 回答 4

2
  • 如果WooFactor纯粹依赖于MyEntity属性,那么它必须在里面完成MyEntity
  • 如果它需要外部信息(例如配置、规则等),那么它需要是Repository 之外的单独服务。我会WooEntity用这个额外的属性在这里创建一个。

在任何情况下,它都不应该在Repository.

于 2011-05-03T13:38:58.870 回答
2

谷歌 CQRS。您需要做的是分离读写关注点。如果实体以外的其他事物需要计算,那么您的答案就一目了然。

于 2011-05-03T13:41:07.493 回答
1

我最近遇到了类似的问题,我需要聚合不同的数据来生成我的实体。我最终决定创建一个服务来处理我的构建Entity以及发生在Entity

使用您的示例它可能如下所示:

public MyEntityService
{
  public MyEntity GetById(int id)
  {
    MyEntity myEntity = _repo.GetById(id);
    myEntity.WooFactor = _wooFactorGenerator.CalculateWooFactor(myEntity);
    return myEntity;
  }
}

最后,这对项目来说是最好的,因为任何交互Entity都是通过服务完成的。

于 2011-05-03T13:43:28.417 回答
0

您管理从存储库获取数据的方式本质上是正确的——因此最好的通用方法是对服务执行相同的操作。拥有一致的架构和方法有很多优势。

The big caveat with that is managing the dependencies; my general assumption is scenarios like this is that the physical data access is abstracted out - so that the model isn't technically tied to SQL, the file system, etc. using this approach will allow you to expose different data from different repositories in a consistent manner.

  • Your idea of using lazy Load is good; and if you abstract out the technical dependencies your main concern with that option goes away.
  • A separate service class might seem like overkill but it's a small price to pay if it means it gives you better control over dependencies.
于 2011-05-04T03:49:08.710 回答