我的代碼部分依賴于同一接口的多個實現,而其他部分依賴于其中一個實現。我正在注冊以下實現:services.AddSingleton<MyInterface, FirstImplementation>();services.AddSingleton<MyInterface, SecondImplementation>();然后在需要時獲取兩種實現,例如:var implementations= serviceProvider.GetServices<MyInterface>();我的問題是當我需要其中之一時,我正在嘗試以下返回空值的方法:var firstImplementation= serviceProvider.GetService<FirstImplementation>();我當然可以使用:var implementations= serviceProvider.GetServices<MyInterface>();foreach (var implementation in implementations){ if (typeof(FirstImplementation) == implementation.GetType()) { FirstImplementation firstImplementation = (FirstImplementation)implementation; }}但我想我可以FirstImplementation 以某種方式直接得到我的。
3 回答

慕萊塢森
TA貢獻1810條經驗 獲得超4個贊
實際上你所做的不是一個好習慣,你可以創建兩個不同的接口繼承自你的基本接口(MyInterface),然后在適當的接口上注冊對應的每個實現,然后在你需要特定實現的代碼部分你可以從 IoC 那里詢問 go 給你重要接口的具體實現:
執行
public interface IFirstImplementation:MyInterface {} public interface ISecondImplementation:MyInterface {}
注冊
services.AddTransient<IFirstImplementation, FirstImplementation>(); services.AddTransient<ISecondImplementation, SecondImplementation>();
用法
var firstImplementation= serviceProvider.GetService<IFirstImplementation>();
- 3 回答
- 0 關注
- 257 瀏覽
添加回答
舉報
0/150
提交
取消