I'm new to StructureMap and have some existing code that I'm working with that uses StructureMap 2.5.4.
There is a class that is constructed using StructureMap that has a constructor that takes IEnumerable<ICar>
as a parameter.
The registry has the following code.
Scan(x =>
{
x.TheCallingAssembly();
x.WithDefaultConventions();
x.AddAllTypesOf<ICar>();
}
);
ForRequestedType<IEnumerable<ICar>>().TheDefault.Is.ConstructedBy(
x => ObjectFactory.GetAllInstances<ICar>());
I'm writing a unit test and have obtained a nested container off the ObjectFactory and have injected an instance using the Inject method. One of the instances of ICar should receive the injected type in its constructor. However it wasn't working and I tracked that down to the ObjectFactory.GetAllInstances() call which doesn't use my nested container.
How can I get this to work?
I also read about StructureMap autowiring arrays and IEnumerable instances but I couldn't get it to work.
Is there a better way to rewrite the above registry code so that an instance of IEnumerable<ICar>
will be created and use the injected type from my nested container?
If you are injecting an instance into a nested container, then you will need to retrieve that instance from the nested container. The static ObjectFactory has its own container, likely the 'parent' container in your case. The parent container does not inherit instances from nested containers.
You do not need to do any specific registration to have all of the instances injected into a class which accepts an IEnumerable
in its constructor. StructureMap will do that automatically. If you have 3 instances of ICar registered in your container, and request an instance of Foo from that container, where Foo has an IEnumerable<ICar>
constructor parameter, Foo will be created with the 3 instances of ICar injected.
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