7

は、私は以下の持っている想像して実装していますがSimpleInjector経由シングルトンの登録と同じインスタンスを返し、異なるインターフェイスのためには、

public interface IocInterface1 { } 

public interface IocInterface2 { } 

public class IocImpl : IocInterface1, IocInterface2 { } 

私が好きだろうと私は介して、上記のクラス/インタフェースのいずれかのインスタンスを取得しようとした場合IoC、タイプごとに1つのシングルトンではなく、まったく同じインスタンスを取得します。たとえば、b1b2は以下の真でなければなりません:

_container.RegisterSingle<IocInterface1, IocImpl>(); 
_container.RegisterSingle<IocInterface2, IocImpl>(); 
_container.RegisterSingle<IocImpl, IocImpl>(); 

var test1 = _container.GetInstance<IocInterface1>(); 
var test2 = _container.GetInstance<IocInterface2>(); 
var test3 = _container.GetInstance<IocImpl>(); 

bool b1 = test1 == test2; 
bool b2 = test2 == test3; 

が、これは可能ですか?

答えて

10

同じ登録で複数のタイプを登録する場合は、実装タイプIocImplのシングルトン登録オブジェクトが必要です。

その後、あなたは別のサービスのためにこの登録を追加するためにAddRegistrationを使用する必要があります。IocInterface1IocInterface2等:

var _container = new Container(); 
var registration = 
    Lifestyle.Singleton.CreateRegistration<IocImpl, IocImpl>(_container); 

_container.AddRegistration(typeof(IocImpl), registration); 
_container.AddRegistration(typeof(IocInterface1), registration); 
_container.AddRegistration(typeof(IocInterface2), registration); 

documenationで説明したように:またRegister multiple interfaces with the same implementation

、あなたも作ることができます代理人を使用したマッピング:

_container.RegisterSingle<IocImpl>(); 
_container.RegisterSingle<IocInterface1>(() => container.GetInstance<IocImpl>()); 
_container.RegisterSingle<IocInterface2>(() => container.GetInstance<IocImpl>()); 

ほとんどの場合、両方の試験葉は機能的に同等であるが、前者が好ましい。

+0

これは私が必要とするものに適しています - しかし、それは 'container.RegisterSingleOpenGeneric()'にも対応していますか?なぜなら、私は '[IocComponent]'を作成したカスタム属性で飾るすべての型をスキャンするアセンブリスキャナーがあり、これもオープンジェネリックに対応しているからです。 –

+0

'RegisterSingleOpenGeneric'は、' ResolveUnregisteredType'イベントで即座に登録を作成するため、少し違って動作します... 'RegisterSingleOpenGeneric'メソッドのロジックを置き換えることなく、どうやってそれを行うことができるか考えなければなりません。しかし、私はスキャンの仕組みとジェネリックタイプの登録方法の詳細を指定するフォローアップの質問をお願いします。 – nemesv

+0

私は@nemesvに同意します:これらの詳細について新しい質問をしてください。この回答は正しいです。それに対して+1。 – Steven

関連する問題