2011-12-20 58 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; 
} 

//------------------------------------------------------------ 

所以,我想實現,不知道如何可以做,如果可能的話,是每當我構建SomeClassSomeOtherClass時總是會獲得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而是試圖解決SomeOtherClass由於容器不知道如何構建IInheritedInterface時將拋出。

我也試過這樣:

_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; 
    })); 

然而,由於某些原因,當我在兩個SomeClassSomeOtherClass他們都最終調用的IInheritedInterface工廠造成死循環調用Resolve()!然後我刪除了IBaseInterface註冊,現在解決SomeClass拋出。

任何想法?

感謝

回答

3

試試這個

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

謝謝!有趣的是,解決方案可能非常簡單,但你從不考慮它。乾杯。 – 2011-12-20 21:57:25

相關問題