2011-12-20 12 views
0

は、私は、次のタイプ持って考えてみましょ同じ実装を返すために:だからユニティファクトリメソッドを持つ複数のインターフェイス登録が

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の工場を呼び出すに終わるの両方SomeClassSomeOtherClassResolve()呼び出す何らかの理由!その後、IBaseInterfaceの登録を取り除き、SomeClassのスローを解決しました。

アイデア?

おかげ

答えて

3

この

container.RegisterType<IBaseInterface, MyClass>(new ContainerControlledLifetimeManager(), new InjectionFactory(ctr => new MyClass())); 
container.RegisterType<IInheritedInterface, MyClass>(); 
+0

感謝をお試しください!ソリューションが非常にシンプルになる可能性はありますが、あなたは決してそれについて考えることは面白いです。乾杯。 –

関連する問題