Search code examples
c#dependency-injectiondryioc

DryIoc Constructor Argument Reused


I have a Container that registers a Presenter class for a View:

Container.Register<ListCellPresenter>();

The Presenter's constructor takes one argument for its view:

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

And I have a View that resolves an instance of the Presenter, passing itself as the argument for the constructor:

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

On the home screen I have multiple instances of this View, which each need their own instance of the Presenter. That part works.

However, it seems that DryIoc continually reuses the first object it received at runtime to satisfy the argument for the constructor. Each new instance of the Presenter receives the first instance of the View when the desire is that they should each receive unique instances.

I have tried various combinations of examples I've found in the docs including:

  • Registering with RegisterDelegate where the delegate explicitly uses Args.Index<ListCellView>(0) to satisfy the dependency
  • Registering with a standard Register using Made.Of(() => new ListCellPresenter(Arg.Of<ListCellView>())
  • Resolving with var getPresenter = Container.Resolve<Func<ListCellView, ListCellPresenter>>(); followed by presenter = getPresenter(this);

Any tips or guidance would be appreciated.


Solution

  • I found that opening named scopes does what you need.

    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) });
    }