我正在尝试创建一个工厂,它将在字典中保存“子”控制器的列表。这些子控制器必须包含工厂,以便它们可以访问其他子控制器。这里是工厂:
public interface IChildControllerFactory
{
IChildController GetChildController(object item);
}
public class ChildControllerFactory : IChildControllerFactory
{
private Dictionary<string, IChildController> _childControllerDictionary;
public ChildControllerFactory(IEnumerable<IChildController> childControllers)
{
var childControllerDictionary = new Dictionary<string, IChildController>();
//code to build dictionary
_childControllerDictionary = childControllerDictionary;
}
public IChildController GetChildController(object item)
{
return _childControllerDictionary.Where(x => x.Key == item.GetType().Name).Select(x => x.Value).First();
}
}
下面是一个子控制器的例子:
public class ChildController : Controller, IChildController<TViewModel, TModel>
{
private IChildControllerFactory _childControllerFactory;
public ChildController(IChildControllerFactory childControllerFactory) //this will cause a circular reference
{
_childControllerFactory = childControllerFactory;
}
public ActionResult GetChildViewModel(object child)
{
var model = _childControllerFactory.GetChildController(child).ToViewModel(survey);
return PartialView("Child.ascx", model);
}
}
和继承的接口:
public interface IChildController<TViewModel, TModel>
{
int Create(object item);
object Save(object item);
object ToViewModel(object item);
}
子控制器全部注册,工厂指定为带有结构映射的单例。
因为子控制器需要Factory,使用依赖注入在构造函数中设置工厂会导致循环引用,因为第一次初始化Factory时,会初始化所有子控制器,每个子控制器都会尝试初始化Factory(即已经在执行)。
如何让工厂实例化所有子控制器,然后从这些子控制器访问它?