Discussions

Ask a Question
Back to all

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

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

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

Hi Matt and thanks.

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

// the override in the spec class

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

        container.Configure(cfg =>
        {
            cfg.For<IEnumerable<IOptionValueParser>>().Use(parsers);
        });
    }

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

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.

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

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.Add() multiple times.

Happy testing! :)

ο»Ώ