亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何注冊兩個實現然后在 .Net Core 依賴注入中獲取一個

如何注冊兩個實現然后在 .Net Core 依賴注入中獲取一個

C#
忽然笑 2021-07-01 13:44:56
我的代碼部分依賴于同一接口的多個實現,而其他部分依賴于其中一個實現。我正在注冊以下實現: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>();


查看完整回答
反對 回復 2021-07-03
  • 3 回答
  • 0 關注
  • 257 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號