は、私は、次のタイプ持って考えてみましょ同じ実装を返すために:だからユニティファクトリメソッドを持つ複数のインターフェイス登録が
public interface IBaseInterface { }
public interface IInheritedInterface : IBaseInterface { }
public class MyClass : IInheritedInterface { }
//------------------------------------------------------------
public interface ISomeInterface { }
public class SomeClass : ISomeInterface {
private readonly IBaseInterface _myInterface;
public SomeClass(IBaseInterface myInterface) {
_myInterface = myInterface;
}
}
//------------------------------------------------------------
public interface ISomeOtherInterface { }
public class SomeOtherClass : ISomeOtherInterface {
private readonly IInheritedInterface _myInterface;
public SomeOtherClass(IInheritedInterface myInterface) {
_myInterface = myInterface;
}
//------------------------------------------------------------
、私が達成しようとしている何をして、可能な場合、行うことができるか疑問に思う、ということですSomeClass
またはSomeOtherClass
のいずれかを作成するときは、常にMyClass
の同じインスタンスを取得することです。この例では、私が欲しいものを説明します。
var someClass = _container.Resolve<SomeClass>();
var someOtherClass = _container.Resolve<SomeOtherClass>();
// At this point, The following assert should pass
Assert.AreSame(someClass._myInterface, someOtherClass._myInterface)
もMyClass
は、他の理由のためのファクトリメソッドを使用して登録する必要があることに注意してください。私は、次のことを試してみました:
_container.RegisterType<IBaseInterface, MyClass>(
perRequestLifetime,
new InjectionFactory((c) =>
{ return FactoryMethod(c); }));
これはSomeClass
を解決しますが、コンテナはIInheritedInterface
を構築する方法を知らないので、SomeOtherClass
を解決しようとするとスローされます。
また、私はこれを試してみました:
_container.RegisterType<IBaseInterface, MyClass(
perRequestLifetime,
new InjectionFactory((c) => {
MyClass myClass;
// Construct object some how...
return myClass;
}));
_container.RegisterType<IInheritedInterface, MyClass(
perRequestLifetime,
new InjectionFactory((c) => {
return c.Resolve<IBaseInterface>() as MyClass;
}));
しかし、私は彼らの両方が無限ループを引き起こしてIInheritedInterface
の工場を呼び出すに終わるの両方SomeClass
とSomeOtherClass
にResolve()
呼び出す何らかの理由!その後、IBaseInterfaceの登録を取り除き、SomeClass
のスローを解決しました。
アイデア?
おかげ
感謝をお試しください!ソリューションが非常にシンプルになる可能性はありますが、あなたは決してそれについて考えることは面白いです。乾杯。 –