【发布时间】:2023-03-07 03:38:02
【问题描述】:
我使用温莎城堡作为我的 IoC 容器,但遇到了一些问题。这在代码中得到了最好的解释,所以我会试一试。 我有一个工厂类,它应该为我提供某个接口的实现:
public interface IObjectCreatorFactory
{
IObjectCreator GetObjectCreator(Type objectType);
}
public interface IObjectCreator
{
T CreateObject<T>(IDataRow data);
bool SupportsType(Type type);
}
工厂类的实现可能如下所示,尽管我不确定这是要走的路: 公共接口 ObjectCreatorFactory:IObjectCreatorFactory { IEnumerable specificCreators; IObjectCreator defaultCreator;
public ObjectCreatorFactory(IEnumerable<IObjectCreator> specificCreators, IObjectCreator defaultCreator)
{
this.specificCreators= specificCreators;
this.defaultCreator= defaultCreator;
}
public IObjectCreator GetObjectCreator(Type objectType)
{
foreach (IObjectCreator creator in specificCreators)
{
if (creator.SupportsType(objectType))
{
return creator;
}
}
return defaultCreator;
}
}
现在这样可以了,但是如果我希望我的 IObjectCreator 实例使用特定的 IObjectCreator 创建子对象,我想调用 ObjectCreatorFactory,这显然会导致循环引用:
public void SpecificObjectCreator:IObjectCreator
{
IObjectCreatorFactory objCreatorFactory;
public SpecificObjectCreator(IObjectCreatorFactory objCreatorFactory)
{
this.objCreatorFactory = objCreatorFactory;
}
T CreateObject<T>(IDataRow data)
{
T obj = new T;
ChildObject childObject = objCreatorFactory.GetObjectCreator(typeof(ChildObject)).CreateObject<ChildObject>(data);
.......
}
bool SupportsType(Type type);
}
这行不通。在这种情况下,创建的对象将引用回工厂以供子对象创建者使用,该怎么做?
【问题讨论】:
标签: dependency-injection inversion-of-control castle-windsor factory