同じインターフェイスの複数の実装に依存するコードの部分と、実装の1つに依存する他の部分があります。
私は次のような実装を登録しています:
services.AddSingleton<MyInterface, FirstImplementation>();
services.AddSingleton<MyInterface, SecondImplementation>();
次に、必要なときに両方の実装を取得します
var implementations= serviceProvider.GetServices<MyInterface>();
私の問題は、それらのいずれかが必要なときに、nullを返す次のものを試しています:
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 件
実際にあなたがしたことは良い習慣ではありません、あなたは2つの異なるを作成することができますインターフェース 基本インターフェースから継承された(MyInterface)そして、適切なインターフェイスに対応する各実装を登録します。その後、特定の実装が必要なコードの部分で、IoCに依頼して、重要なインターフェイスの特定の実装を返します。
実装public interface IFirstImplementation:MyInterface {} public interface ISecondImplementation:MyInterface {}
services.AddTransient<IFirstImplementation, FirstImplementation>(); services.AddTransient<ISecondImplementation, SecondImplementation>();
var firstImplementation= serviceProvider.GetService<IFirstImplementation>();
Microsoft.Extensions.Dependencyinjection
依存性注入の基本的なニーズを提供し、他にもIoC container
があります 問題を解決できる.NET用のフレームワーク。たとえば、次のようなAutofacの名前付きサービスを使用できます。//registration method var builder = new ContainerBuilder(); ... builder.RegisterType<FirstImplementation>().Named<MyInterface>("first"); builder.RegisterType<SecondImplementation>().Named<MyInterface>("second"); //resolve method var firstImplementation = container.ResolveNamed<MyInterface>("first");
より複雑なシナリオでは、インデックスと属性による解決をサポートするキー付きサービスを使用できます。
Autofacを使用する場合は、インスタンススコープにも注意を払う必要があります。
関連した質問
- C#ILogger依存性注入エラー:引数がありません
- netコアのJavaScriptファイルを更新できません
- データ注釈での列挙型の使用
- 私のプロジェクトはnetstandard21と互換性がありません。私のプロジェクトは以下をサポートしています:netcore 30
- CosmosDb SDK v3は、一括挿入中に自動的に再試行しますか?
- CefSharpWPFは、自己完結型ファイルNETCoreとして実行されません
- APIの結果は、Json(繰り返される親)のネストされた不要なクラスをすべて埋めます
- NET Core TestServerは、存在しないパスへのPOSTリクエストに対して404ではなくステータス200を返します
- Net CoreワーカーサービスがWindowsサービスとして実行されている場合、log4netconfigが見つかりません
- EFで生成された2つの外部キー
コンテナは
FirstImplementation
を解決する方法を知っていますMyInterface
を求められたとき 、FirstImplementation
を解決する方法が伝えられていない 特にFirstImplementation
を求められたとき 。組み込みのサービスコンテナは、フレームワークとその上に構築されたほとんどのコンシューマアプリケーションの基本的なニーズに応えることを目的としています。必要最低限の機能であり、必要に応じて動作するように明示的に設定する必要があります。実装を明示的に要求された場合、実装を取得する方法も伝える必要があります。
だから今、あなたはあなたの
FirstImplementation
を得ることができます 直接、同じインスタンスを取得する