重用DryIoc构造函数参数

时间:2019-01-10 22:47:01

标签: c# dependency-injection dryioc

我有一个Container,它为视图注册了Presenter类:

Container.Register<ListCellPresenter>();

Presenter的构造函数为其视图采用一个参数:

public ListCellPresenter(ListCellView view) {
     this.view = view;
}

我有一个View可以解析Presenter的一个实例,并将自身作为构造函数的参数传递:

Container.Resolve<ListCellPresenter>(new object[] {this});

在主屏幕上,我有这个View的多个实例,每个实例都需要自己的Presenter实例。那部分起作用。

但是,似乎DryIoc不断重用在运行时收到的第一个对象,以满足构造函数的参数。当希望每个Presenter的新实例都应该接收唯一的实例时,它们会收到View的第一个实例。

我尝试了在文档中找到的示例的各种组合,包括:

  • RegisterDelegate注册,其中委托人明确使用Args.Index<ListCellView>(0)来满足依赖性
  • 使用Register向标准Made.Of(() => new ListCellPresenter(Arg.Of<ListCellView>())注册
  • 先解决var getPresenter = Container.Resolve<Func<ListCellView, ListCellPresenter>>();,再解决presenter = getPresenter(this);

任何提示或指导将不胜感激。

2 个答案:

答案 0 :(得分:2)

该问题确实是一个错误,并且已在最新的预览版本中修复: https://github.com/dadhi/DryIoc/issues/29

答案 1 :(得分:1)

我发现打开命名作用域可以满足您的需求。

var container = new Container();
container.Register<TargetClass>();
using (var scope = container.OpenScope("View_1"))
{
    var instanceA = scope.Resolve<TargetClass>(new[] { typeof(string) });    
}

using (var scope = container.OpenScope("View_2"))
{
    var instanceB = scope.Resolve<TargetClass>(new[] { typeof(int) });
}