C# 使用存储库模式创建对象的新实例的正确方法是什么?

C# 使用存储库模式创建对象的新实例的正确方法是什么?,c#,repository,design-patterns,C#,Repository,Design Patterns,我一直在使用c#和.net来处理存储库模式 我的问题是创建someRepositoryObject的新实例。到目前为止,我所看到的所有示例都使用了如下内容: using(ISomeRepository someRepository = new SomeRepository().getRepository()) { IsomeRepositoryObject repObj = new someRepositoryObject(); } 调用newsomerepositoryobject是

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

我的问题是创建
someRepositoryObject
的新实例。到目前为止,我所看到的所有示例都使用了如下内容:

using(ISomeRepository someRepository = new SomeRepository().getRepository())
{
    IsomeRepositoryObject repObj = new someRepositoryObject();
}
调用
newsomerepositoryobject
是否会首先消除使用接口的问题?是否最好采取以下措施:

using(ISomeRepository someRepository = new SomeRepository().getRepository())
{
    IsomeRepositoryObject repObj = someRepository.NewsomeRepositoryObject();
}
因此,存储库本身返回所需对象的一个新实例,而调用代码不知道传递给它的类,只知道它的类型是
isormonepositoryObject

这对我来说都是新的,所以我可能错过了一些明显的东西


任何帮助都将不胜感激。

我将使用IOC容器提供帮助

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

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

}

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

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

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

只是出于好奇,为什么
new SomeRepository().getRepository()
而不是
new SomeRepository()
或者类似于
RepositoryFactory.getSomeRepository()
或者甚至
SomeRepository.getRepository()
?想想看,没有理由!我使用getRepository拉入一个web.config appsetting,然后用它返回正确的存储库类型。这段代码可以添加到SomeRepository的构造函数中。这是我在圣诞假期前玩的东西,所以我要重新思考一下。