我有一個很好的答案my question here,但我不知道我是否可以申請這個問題的答案我的項目,因爲我顯然需要使用代碼這樣的事情在我的控制器:如何從Controller中爲存儲庫的構造函數指定參數?
return DBConnectionStrings[DBSpecifier].Get(ID, CountToFetch);
.. (其中DBConnectionStrings是一個字典),而不是:
return deptsRepository.Get(ID, CountToFetch);
真正的問題/挑戰是,我需要我的Repositorys'建設者能夠接受ARG,以便相應地更改數據庫連接字符串。然後,這些構造函數可以使用字典建議在先前的帖子中,以便開始而不是像這樣:
public DuckbillRepository()
{
using (var conn = new OleDbConnection(
@"Provider=Microsoft.Jet.OLEDB.4.0;User ID=NRBQ;Password=NRBQRotPS;Data
Source=C:\Platypus\DATA\PlatypusFlipper03.MDB;Jet OLEDB:System
database=C:\Platypus\Data\duckbill.mdw"))
{
...這將是這樣的:
public DuckbillRepository(string DBToUse)
{
using (var conn = new OleDbConnection(
string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;User
ID=NRBQ;Password=NRBQRotPS;Data Source=C:\Platypus\DATA\{0}.MDB;Jet
OLEDB:System database=C:\Platypus\Data\duckbill.mdw", DBToUse))
{
但我怎麼能,從Controller中爲Repository的構造函數指定一個arg(這是用於填充Repository的方法然後查詢的數據存儲)?目前,典型的控制器是這樣的:
static readonly IDuckbillRepository duckbillsRepository = new DuckbillRepository();
public IEnumerable<Duckbill> GetBatchOfDuckbillsByStartingID(int ID, int CountToFetch)
{
return duckbillsRepository.Get(ID, CountToFetch);
}
最好的辦法/最近我可以想出現在是我需要這樣的事情,而不是:
public IEnumerable<Duckbill> GetBatchOfDuckbillsByStartingID(string DBInstance, int ID, int CountToFetch)
{
IDuckbillRepository duckbillsRepository = new DuckbillRepository(DBInstance);
return duckbillsRepository.Get(ID, CountToFetch);
}
我是在右邊跟蹤或咆哮錯誤的樹?
使用像NInject一個DI容器。事實上,通常的做法不是將arg傳遞給資源庫的構造函數,而是將整個資源庫對象傳遞給控制器。 –
客戶端通過http傳遞一個倉庫對象給控制器?這不是問題的過度複雜化,還有違反DRY和潛在危險的傳播應該是服務器特定的實現細節?我不是說你錯了,我只是感到驚訝/困惑。 –
不,客戶端將字符串傳遞給服務器。 NInject工廠使用字符串來實例化回購並將其傳遞給控制器。 –