JChristian
JChristian

Reputation: 4170

How to resolve the same dependency between a child and parent class with structuremap

I have a couple classes that look like this

public class ParentClass
{
    public ParentClass(IChildClass childClass, IDependency dependency)
    { }
}

public ChildClass : IChildClass
{
    public ParentClass(IDependency dependency)
    { }
}

Is there a way to register ParentClass via StructureMap so that it resolves with an IDependency that is the same instance between ParentClass and IChildClass?

Edit

To clarify, I'm looking to resolve ParentClass as if it had been manually created like this (from MrFox's answer):

IDependency dependency = new Dependency();
ChildClass childClass = new ChildClass(dependency);
ParentClass parentClass = new ParentClass(childClass, dependency);

IDependency should not be a singleton. I want to resolve ParentClass with a different IDependency every time.

Upvotes: 4

Views: 729

Answers (3)

Bassetassen
Bassetassen

Reputation: 21814

This code here will give you the same IDependency for Parent and child.

var container = new Container(x => {
            x.For<IChildClass>().Use<ChildClass>();
            x.For<IDependency>().Use<Dependency>();
        });

var firstParent = container.GetInstance<ParentClass>();

If you where to ask for another container.GetInstance<ParentClass>(); it will give you a new parent, child and dependency. If you would like to have IDependency as a singelton so it will be used everytime you ask for a Parent or child class, then you can register it with the Singeleton method: x.For<IDependency>().Singleton().Use<Dependency>();

Upvotes: 4

Paul Phillips
Paul Phillips

Reputation: 6259

I can't answer whether StructureMap can do this. But using a factory to create the child from within the parent gives you an IoC-container-agnostic solution.

public interface IChildFactory {
  IChild Create(IDependency dependency);
}

public class ParentClass
{
  private readonly IChildClass _child;

  public ParentClass(IChildFactory childFactory, IDependency dependency)
  {
    _child = childFactory.Create(dependency);
  }
}

class ChildFactory : IChildFactory 
{
  IChildClass Create(IDependency dependency)
  {
    return new ChildClass(dependency);
  }
}

Now all IChild instances would be created by this simple factory instead of through the IoC container.

Upvotes: 2

MrFox
MrFox

Reputation: 5126

Pass a reference of one IDependency object to both constructors:

IDependency dependency = new Dependency();
ChildClass childClass = new ChildClass(dependency);
ParentClass parentClass = new ParentClass(childClass, dependency);

Upvotes: 1

Related Questions