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
而是试图解决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;
}));
然而,由于某些原因,当我在两个SomeClass
和SomeOtherClass
他们都最终调用的IInheritedInterface
工厂造成死循环调用Resolve()
!然后我删除了IBaseInterface注册,现在解决SomeClass
抛出。
任何想法?
感谢
谢谢!有趣的是,解决方案可能非常简单,但你从不考虑它。干杯。 – 2011-12-20 21:57:25