Dependency injection Unity-使用工厂方法注册多个接口以返回相同的实现

Dependency injection Unity-使用工厂方法注册多个接口以返回相同的实现,dependency-injection,unity-container,Dependency Injection,Unity Container,假设我有以下类型: 公共接口IBaseInterface{} 公共接口IInheritedInterface:IBaseInterface{} 公共类MyClass:IInheritedInterface{} //------------------------------------------------------------ 公共接口{} 公共类SomeClass:接口{ 专用只读IBaseInterface\u myInterface; 公共SomeClass(IBaseInterfa

假设我有以下类型:

公共接口IBaseInterface{}
公共接口IInheritedInterface:IBaseInterface{}
公共类MyClass:IInheritedInterface{}
//------------------------------------------------------------
公共接口{}
公共类SomeClass:接口{
专用只读IBaseInterface\u myInterface;
公共SomeClass(IBaseInterface myInterface){
_myInterface=myInterface;
}
}
//------------------------------------------------------------
公共接口{}
公共类SomeOtherClass:ISomeOtherInterface{
专用只读IInheritedInterface\u myInterface;
公共SomeOtherClass(IInheritedInterface myInterface){
_myInterface=myInterface;
}
//------------------------------------------------------------
因此,如果可能的话,我试图实现并想知道如何实现的是,每当我构建
SomeClass
SomeOtherClass
时,总是得到相同的
MyClass
实例。这个例子解释了我想要的:

var someClass=\u container.Resolve();
var someOtherClass=_container.Resolve();
//此时,应通过以下断言
Assert.AreName(someClass.\u myInterface,someOtherClass.\u myInterface)
另请注意,出于其他原因,
MyClass
需要使用工厂方法注册。我尝试了以下方法:

\u container.RegisterType(
佩雷斯特一生,
新注射剂工厂((c)=>
{return FactoryMethod(c);});
这将解析
SomeClass
,但在尝试解析
SomeOtherClass
时将抛出,因为容器不知道如何构造
IInheritedInterface

我也试过:

\u container.RegisterType{
MyClass MyClass;
//如何构造对象。。。
返回myClass;
}));
_container.RegisterType{
将c.Resolve()作为MyClass返回;
}));
然而,由于某种原因,当我在
SomeClass
SomeOtherClass
上调用
Resolve()
时,它们最终都调用了
IInheritedInterface
的工厂,导致了一个无休止的循环!然后我删除了IBaseInterface注册,现在解析
SomeClass
抛出

有什么想法吗

谢谢你试试这个

container.RegisterType(新的ContainerControlledLifetimeManager(),新的InjectionFactory(ctr=>new MyClass());
container.RegisterType();
试试这个

container.RegisterType(新的ContainerControlledLifetimeManager(),新的InjectionFactory(ctr=>new MyClass());
container.RegisterType();

谢谢!有趣的是,一个解决方案可能非常简单,但你从未想过。干杯。谢谢!有趣的是,一个解决方案可能非常简单,但你从未想过。干杯。