gpt4 book ai didi

repository-pattern - 如何在存储库模式中为同一接口(interface)使用两个数据存储?

转载 作者:行者123 更新时间:2023-12-04 07:52:54 29 4
gpt4 key购买 nike

我清楚地了解什么是存储库模式及其从 TDD 的角度来看的重要性。我也明白为应用程序切换底层数据存储是多么容易,因为存储库充当数据访问逻辑的窗口。

我没有得到的是如何同时支持多个数据存储。这是一个示例,假设我已经定义了一个存储库 IPersonRepository,它有两个实现,要求是读取 XML 文件并存储到 SQL 数据库中,反之亦然。

数据访问层

public interface IPersonRepository  
{
Person GetPersonById(int id);
}

public class PersonRepositorySQL : IPersonRepository
{
public Person GetPersonById(int id)
{
// get person from sql db (using ado.net)
}
}

public class PersonRepositoryXML : IPersonRepository
{
public Person GetPersonById(int id)
{
// get person from xml file
}
}

业务逻辑层

public PersonService   
{
private IPersonRepository personRepository;

public PersonService(IPersonRepository personRepository)
{
this.personRepository = personRepository;
}

public Person GetPersonById(int id)
{
personRepository.GetPersonById(id);
}
}

问题(按重要性排序):

  1. 这是否意味着我每次都必须通过分别传递 PersonRepositorySQL 和 PersonRepositoryXML 从 db 和 xml 读取数据来实例化两个 PersonService 对象?
  2. 为了完成上述操作,我必须在上层(主要是演示)添加对存储库的引用?如何避免这种情况?
  3. DAL 是保存存储库的好地方吗?
  4. 可以将 BLL 类命名为 Service ex: PersonService 吗?

我意识到帖子已经变得很长,但我想把所有引起混淆的东西都记在心里。

-- 内华达

最佳答案

Does this mean I have to instantiate two PersonService objects everytime for reading data from db and xml by passing PersonRepositorySQL and PersonRepositoryXML respectively?

不,但是您正朝着正确的方向前进。我会将两个存储库注入(inject)服务(两个构造函数参数)并编写两个服务方法,一个以一种方式移动数据,另一个以另一种方式移动数据。

连接两个存储库应该是服务的责任,而不是客户端。

然后使用 IoC 容器来设置服务实例并将其提供给客户端,绝对不建议到处使用 New Services()。您需要查找最适合您使用的任何演示技术的 IoC 工具/方法。

For doing above, I have to add reference to repositories in upper level (mostly presentation)? How can this be avoided?

这对于演示来说没问题,因为它需要知道将什么注入(inject)到服务实例中,演示是您唯一需要直接引用具体 DAL 类的地方,并且仅出于这个原因。

我发现谷歌搜索 VS 分层架构项目结构(或类似的)帮助我在我不太确定时返回。

Is DAL good place to keep repositories?

那是他们应该在的地方。您的 DAL 通常用于接触硬件的所有内容,即文件、数据库、webapi。

Is it OK to name a BLL class as Service ex: PersonService?

当然。它简短、亲切,并告诉人们(和其他开发人员)它是什么(服务)以及它的职责是什么(人)

关于repository-pattern - 如何在存储库模式中为同一接口(interface)使用两个数据存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21762089/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com