StructureMap and IEnumerable <T> Injection

I am new to StructureMap and have some existing code I'm working with that uses StructureMap 2.5.4.

There is a class built using StructureMap that has a constructor that takes an 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 write unit test and get a nested container from an ObjectFactory and injected an instance using the Inject method. One of the ICar instances should get the entered type in its constructor. However, it did not work, and I tracked it until I called ObjectFactory.GetAllInstances (), which does not use my nested container.

How can I make this work?

I also read about autwiring StructureMap arrays and IEnumerable instances, but I couldn't get it to work.

Is there a better way to rewrite the registry code above to create an instance of IEnumerable<ICar> and use the entered type from my nested container?

+7
source share
1 answer

If you insert an instance into a nested container, you will need to extract that instance from the nested container. The static ObjectFactory object has its own container, most 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 so that all instances are injected into a class that accepts IEnumerable in its constructor. StructureMap will do this automatically. If you have 3 instances of ICar registered in your container, and request a Foo instance from that container, where Foo has an IEnumerable<ICar> constructor parameter, Foo will be created with the three ICAR instances that were entered.

+7
source

All Articles