請記住,如果不需要,我不打算添加其他依賴項。此外,大多數(shù)想法已經(jīng)來自我在尋找解決方案時發(fā)現(xiàn)的這里 (stackoverflow.com)。假設(shè)我有一個 IPrinterRepository 接口,我有多個不同的實現(xiàn)。例如 EpsonRepository 和 CanonRepository、HPRepository 和許多其他人一樣實現(xiàn) IPrinterRepository所以現(xiàn)在我像這樣在ConfigurationServices 中注冊了我的服務(wù)services.AddTransient<EpsonRepository>();services.AddTransient<HPRepository>();services.AddSingleton<IPrinterRepositoryResolver, PrinterRepositoryResolver>();- V1 -現(xiàn)在,我一直在我的數(shù)據(jù)庫中為某些特定用戶激活的每臺活動打印機(jī)保存一個 PRINTER_CODE。PrinterCode 是一類常量字符串。PrinterRepositoryResolver 處理正確實現(xiàn)的選擇。所以有一種方法可以使用 switch 語句做到這一點(diǎn)。public IPrinterRepository GetRepository(string key){ switch (key) { case PrinterCode.Epson: return (IPrinterRepository)_serviceProvider.GetService(typeof(EpsonRepository)); case PrinterCode.HP: return (IPrinterRepository)_serviceProvider.GetService(typeof(HPRepository)); default: throw new KeyNotFoundException("Sevice not implemented or not supported any more!"); }}- V2 -或者我可以按類型選擇正確的實現(xiàn),這樣我就不必使用 PRINTER_CODE 或維護(hù) switch 語句。例子而不是 PRINTER_CODE 將 DB 中實現(xiàn)的 fullName 保存為字符串,并在以后需要時使用它來選擇正確的實現(xiàn)。public IPrinterRepository GetRepository(string ImplementationName){ var repoType= Type.GetType(ImplementationName); return (IPrinterRepository)_serviceProvider.GetService(repoType);}這一切都適用于我的開發(fā)環(huán)境,但我不知道是否可以。就個人而言,我不喜歡這種開關(guān),因為每次添加新的打印機(jī)實現(xiàn)時,都必須有人維護(hù) PrinterCodes 和開關(guān)。但是,保存一個帶有命名空間的長字符串作為選擇鍵在某種程度上很難看,我覺得可能還有更多我不知道的缺點(diǎn)。是否有一些調(diào)整或更好的想法,以便我可以以正確的方式做到這一點(diǎn)。
- 1 回答
- 0 關(guān)注
- 155 瀏覽
添加回答
舉報
0/150
提交
取消