0

我正在尝试创建一个工厂,它将在字典中保存“子”控制器的列表。这些子控制器必须包含工厂,以便它们可以访问其他子控制器。这里是工厂:

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(即已经在执行)。

如何让工厂实例化所有子控制器,然后从这些子控制器访问它?

4

1 回答 1

1

让我们考虑一下。AchildController只能在分配了工厂权限的情况下工作?所以在childFactory创建 a 之前, 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);
}

我没有测试它,但我没有看到具体对象有必要在构造函数中传递工厂,因为您将这个对象的字典存储在您的工厂中。

于 2012-07-24T00:11:02.300 回答