Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 705
JChristian Avatar asked Oct 19 '25 13:10

JChristian


1 Answers

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

like image 134
Bassetassen Avatar answered Oct 22 '25 03:10

Bassetassen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!