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.
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With