我正在尝试创建一个工厂,它将在字典中保存一个“子”控制器列表。这些子控制器必须包含工厂,以便它们可以访问其他子控制器。这是工厂:
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时,它将初始化所有子控制器,并且每个子控制器将尝试初始化工厂(已经在执行)。
如何让工厂实例化所有子控制器,然后从这些子控制器访问它?
答案 0 :(得分:1)
让我们考虑一下。 childController
只有在分配了工厂权限后才能使用?因此,在创建childFactory
之前,childControll实际上是无用的。那说我会做点什么:
public class ChildController : Controller, IChildController<TViewModel, TModel>
{
private IChildControllerFactory _childControllerFactory;
public ChildController()
{
}
public void setChildControllerFactory( IChildControllerFactory childControllerFactory )
{
_childControllerFactory = childControllerFactory;
}
public ActionResult GetChildViewModel(object child)
{
var model = _childControllerFactory.GetChildController(child).ToViewModel(survey);
return PartialView("Child.ascx", model);
}
}
所以你的ChildControllerFactory
会是这样的:
public ChildControllerFactory(IEnumerable<IChildController> childControllers)
{
var childControllerDictionary = new Dictionary<string, IChildController>();
_childControllerDictionary = childControllerDictionary;
for(IChildController i in _childControllerDictionary) i.setChildControllerFactory(this);
}
我没有测试它,但我没有看到具体对象的必要性,因为你在工厂中存储了这些对象的字典,所以工厂传递了工厂。