【问题标题】:What is the correct way to create a new instance of a object using the repository pattern?使用存储库模式创建对象的新实例的正确方法是什么?
【发布时间】:2011-01-05 11:59:47
【问题描述】:

我一直在使用 c# 和 .net 使用存储库模式。

我的问题是关于创建someRepositoryObject 的新实例。到目前为止我看到的所有例子都使用这样的东西:

using(ISomeRepository someRepository = new SomeRepository().getRepository())
{
    IsomeRepositoryObject repObj = new someRepositoryObject();
}

调用new someRepositoryObject 不是首先消除了使用接口的意义吗?这样做会更好:

using(ISomeRepository someRepository = new SomeRepository().getRepository())
{
    IsomeRepositoryObject repObj = someRepository.NewsomeRepositoryObject();
}

所以存储库本身返回了所需对象的新实例,调用代码不知道传递给它的类,只是知道它的类型为ISomeRepositoryObject

这对我来说是全新的,所以我可能会遗漏一些明显的东西!

任何帮助将不胜感激。

【问题讨论】:

  • 只是出于好奇,为什么new SomeRepository().getRepository() 而不仅仅是new SomeRepository() 或类似RepositoryFactory.getSomeRepository() 甚至SomeRepository.getRepository()
  • 想一想,没有理由!我正在使用 getRepository 来拉入 web.config appsetting,然后用于返回正确的存储库类型。这段代码可以添加到 SomeRepository 的构造函数中。
  • 其实看代码,我是用 .getSomeRepository() 返回一个 IsomeRepository 对象。这是我在圣诞假期前一直在玩的东西——所以我再想一想。

标签: c# repository design-patterns


【解决方案1】:

通常我使用您描述的第二种方式并让存储库创建一个新实例。原因是 - 正如你所提到的 - 我试图将接口的实现与使用存储库的代码分开。

【讨论】:

    【解决方案2】:

    我会使用 IOC Containers 来提供帮助。

    Ninject 是一个很好的解决方案。例如,在我的 MVC 程序中,我所有的控制器都需要一些服务:

    public class SampleController: Controller {
        public SampleController(IService service) {}
    
    }
    

    IService 由 Ninject 注入,只有 global.asax.cs 需要确认具体类。

    【讨论】:

      【解决方案3】:

      你刚才描述的是抽象工厂模式。 如果是存储库,最好使用 IoC 容器来创建新对象。在这种情况下,您根本不会使用 new 关键字,您将只使用抽象。 Repository by Martin Fowler

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-22
        • 2013-10-15
        • 1970-01-01
        相关资源
        最近更新 更多