tags:

views:

100

answers:

0

Hi :)

I have this odd problem with StructureMap with regards to using the MissingNamedInstanceIs feature. When doing _containerInstance.GetInstance<T>("key") vs. ObjectFactory.GetNamedInstance<T>("key") I get the following error:

StructureMap.StructureMapException : StructureMap Exception Code:  200
Could not find an Instance named "key" ...

If you try out the following code you'll see that the first test fails, but the second passes:

[TestFixture]
public class ObjectFactoryTests
{
    private readonly IContainer _container;

    public ObjectFactoryTests()
    {
        _container = new Container();
        _container.Configure(x =>
          {
              x.ForRequestedType<IFoo>().AddInstances(z => z.OfConcreteType<Foo>());
              x.ForRequestedType<IFoo>().MissingNamedInstanceIs.OfConcreteType<FooBar>();
          });

        ObjectFactory.Initialize(x =>
        {
            x.ForRequestedType<IFoo>().AddInstances(z => z.OfConcreteType<Foo>());
            x.ForRequestedType<IFoo>().MissingNamedInstanceIs.OfConcreteType<FooBar>();
        });
    }

    [Test]
    public void missing_namedinstance_fails_when_using_container_instance()
    {
        var foo = _container.GetInstance<IFoo>();
        var namedFoo = _container.GetInstance<IFoo>("missing");
        // Kaboom!
    }

    [Test]
    public void missing_namedinstance_works_when_using_static_container()
    {
        var namedFoo = ObjectFactory.GetNamedInstance<IFoo>("missing");

        Assert.AreEqual(namedFoo.GetType(), typeof(FooBar));
    }

    public interface IFoo { }
    public class Foo : IFoo { }
    public class FooBar : IFoo {}
}

Does anyone know why the behavior is different and what I am doing wrong?

Best Regards, ahjohannessen