![](/img/trans.png)
[英]What's the correct way to implement a web service with the repository pattern
[英]What is the correct way to create a new instance of a object using the repository pattern?
我一直在使用c#和.net來研究存儲庫模式。
我的問題是關於創建someRepositoryObject
新實例。 到目前為止,我所看到的所有示例都使用類似以下的內容:
using(ISomeRepository someRepository = new SomeRepository().getRepository())
{
IsomeRepositoryObject repObj = new someRepositoryObject();
}
調用new someRepositoryObject
不會new someRepositoryObject
消除使用接口的new someRepositoryObject
嗎? 這樣做會更好嗎:
using(ISomeRepository someRepository = new SomeRepository().getRepository())
{
IsomeRepositoryObject repObj = someRepository.NewsomeRepositoryObject();
}
因此,存儲庫本身返回所需對象的新實例,並且調用代碼不知道將傳遞給該對象的類,只是它的類型為ISomeRepositoryObject
。
這對我來說是全新的,所以我可能會遺漏一些明顯的東西!
任何幫助,將不勝感激。
我會使用IOC容器來提供幫助。
Ninject是一個很好的解決方案。 例如,在我的MVC程序中,我所有的控制器都需要一些服務:
public class SampleController: Controller {
public SampleController(IService service) {}
}
IService由Ninject注入,僅global.asax.cs需要確認具體的類。
通常,我使用您描述的第二種方式,並讓存儲庫創建一個新實例。 正如您所提到的,原因是-我也試圖將接口的實現與使用存儲庫的代碼分開。
您剛剛描述的是抽象工廠模式。 在存儲庫的情況下,最好使用IoC容器創建新對象。 在這種情況下,您根本不會使用new關鍵字,而只能使用抽象。 Martin Fowler的存儲庫
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.