c# - 域建模 - 实现属性或 POCO 的接口(interface)?

标签 c# design-patterns repository

我正在制作一个工具的原型(prototype),该工具将通过 SOAP API 将文件导入到基于 Web 的应用程序,并对我尝试通过 C# 接口(interface)导入的内容进行建模,以便我可以将 Web 应用程序的模型数据包装在我可以处理的内容中.

public interface IBankAccount
{
    string AccountNumber { get; set; }
    ICurrency Currency { get; set; }
    IEntity Entity { get; set; }
    BankAccountType Type { get; set; }
}

internal class BankAccount
{
    private readonly SomeExternalImplementation bankAccount;

    BankAccount(SomeExternalImplementation bankAccount)
    {
        this.bankAccount = bankAccount;
    }

    // Property implementations
}

然后我有一个存储库,它返回 IBankAccount 或其他任何东西的集合,还有一个工厂类,用于在我需要时为我创建 BankAccounts。

我的问题是,这种方法会给我带来很多痛苦,创建 POCO 会更好吗?我想将所有这些放在一个单独的程序集中,并完全分离数据访问和业务逻辑,仅仅是因为我正在处理一个关于数据在线存储位置的移动目标。

最佳答案

这正是我使用的方法,而且我从来没有遇到过任何问题。在我的设计中,任何来自数据访问层的东西都被抽象为一个接口(interface)(我将它们称为数据传输契约)。然后在我的域模型中,我使用静态方法从这些数据传输对象创建业务实体。

interface IFooData
{
    int FooId { get; set; }
}

public class FooEntity
{
    static public FooEntity FromDataTransport(IFooData data)
    {
        return new FooEntity(data.FooId, ...);
    }
}

它在您的域模型实体从多个数据契约收集数据时非常方便:

public class CompositeEntity
{
    static public CompositeEntity FromDataTransport(IFooData fooData, IBarData barData)
    {
        ...
    }
}

与您的设计相反,我不提供工厂来创建数据传输契约的具体实现,而是提供委托(delegate)来编写值并让存储库负责创建具体对象

public class FooDataRepository
{
    public IFooData Insert(Action<IFooData> insertSequence)
    {
        var record = new ConcreteFoo();

        insertSequence.Invoke(record as IFooData);

        this.DataContext.Foos.InsertOnSubmit(record); // Assuming LinqSql in this case..

        return record as IFooData;
    }
}

用法:

IFooData newFoo = FooRepository.Insert(f =>
    {
        f.Name = "New Foo";
    });

虽然在我看来工厂实现是一个同样优雅的解决方案。回答你的问题,根据我对一种非常相似的方法的经验,我从来没有遇到过任何重大问题,我认为你在这里走在正确的轨道上:)

关于c# - 域建模 - 实现属性或 POCO 的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4872989/

相关文章:

java - 策略模式的鸭子示例

Android Studio 从其他存储库导入模块的最佳方式

linux - 从 http ://repo_path to svn://repo_path 切换 SVN 存储库名称

c# - 类型 'System.Data.Common.DbTransaction' 在未引用的程序集中定义。您必须添加对程序集的引用

c# - 从另一个项目/程序集访问 resx 文件

c# - 工作单元模式如何容纳对新聚合的引用?

java - 状态模式 : Identify state class type from string

android - repo 同步挂起

c# - 从开始到结束所用的时间,精度为 20 毫秒

c# - 托管环境中的临时内存