Using ConfigureContainer to pass an IEnumerable<T> isn't playing nice

Solved!
Posted in General by Sean Rock Fri Nov 17 2017 12:20:15 GMT+0000 (UTC)·6·Viewed 189 times

I'm trying to write a spec for a class that takes as its ctor parameter an IEnumerable<T> object. I'm overriding ConfigureContainer and specifying a List<T> of real objects however the sut isn't seeing those values. Any ideas?
Matt Honeycutt
Nov 17, 2017

Can you post your ConfigureContainer code and the ctor from the class you're injecting into?

Sean Rock
Nov 17, 2017

Hi Matt and thanks.

// the ctor of the ValueParserFactory class (ioc is autofac)
public ValueParserFactory(IEnumerable<IOptionValueParser> parsers)
{
_parsers = parsers;
}

// the override in the spec class

protected override void ConfigureContainer(IContainer container)
{
List<IOptionValueParser> parsers = new List<IOptionValueParser>()
{
new FractionXmlParser(),
new SpecialXmlParser(),
new TextParser()
};

        container.Configure(cfg =>
        {
            cfg.For<IEnumerable<IOptionValueParser>>().Use(parsers);
        });
    }
Sean Rock
Nov 17, 2017

ok that came out all wrong... hopefully you can make sense of it

Matt Honeycutt
Nov 17, 2017

Yup, I can read it! :)

Try this config code instead:

container.Configure(cfg => {
cfg.For<IOptionValueParser>().Add<FractionXmlParser>();
cfg.For<IOptionValueParser>().Add<SpecialXmlParser>();
cfg.For<IOptionValueParser>().Add<TextParser>();
});

Let me know if that works. If so, I can explain why.

Sean Rock
Nov 17, 2017

Cool thats done it. Thanks Matt you're a star!

Matt Honeycutt
Nov 17, 2017

Awesome! So just for reference, the reason that worked is because of how StructureMap resolves things. When you have a ctor that takes in an IEnumerable of some dependency, what it actually "asks" StructureMap for is to provide all instances of the requested type. So you don't have to explicitly register an IEnumerable or IList, you just call cfg.For<T1>.Add<T2>() multiple times.

Happy testing! :)


Matt Honeycutt marked this as solved
Markdown is allowed