odd behavior when using default instance and named instance

36 views
Skip to first unread message

stig

unread,
Sep 21, 2011, 3:53:47 AM9/21/11
to structuremap-users
Is anybody able to explain the following behavior?

Especially why TestInitializeAndConfigure_Fails failes when
TestUseAndAdd does not.
.. and why TestUse_Fails failes when TestUseOrderChanged does not.

Thanks

interface IResource {}
class TheFirstResource : IResource {}
class TheSecondResource : IResource {}

[TestFixture]
class Test
{
[Test]
public void TestUse_Fails()
{
ObjectFactory.Initialize(init =>
{

init.For<IResource>().Singleton().Use<TheFirstResource>();

init.For<IResource>().Singleton().Use<TheSecondResource>().Named("test");
});

IResource r1 = ObjectFactory.GetInstance<IResource>();
IResource r2 =
ObjectFactory.GetNamedInstance<IResource>("test");

Console.WriteLine(string.Format("TestUse_Fails
\n{0}\n{1}", r1, r2));
}

[Test]
public void TestUseOrderChanged()
{
ObjectFactory.Initialize(init =>
{

init.For<IResource>().Singleton().Use<TheSecondResource>().Named("test");

init.For<IResource>().Singleton().Use<TheFirstResource>();
});

IResource r1 = ObjectFactory.GetInstance<IResource>();
IResource r2 =
ObjectFactory.GetNamedInstance<IResource>("test");

Console.WriteLine(string.Format("TestUseOrderChanged
\n{0}\n{1}", r1, r2));
}

[Test]
public void TestUseAndAdd()
{
ObjectFactory.Initialize(init =>
{

init.For<IResource>().Singleton().Use<TheFirstResource>();

init.For<IResource>().Singleton().Add<TheSecondResource>().Named("test");
});

IResource r1 = ObjectFactory.GetInstance<IResource>();
IResource r2 =
ObjectFactory.GetNamedInstance<IResource>("test");

Console.WriteLine(string.Format("TestUseAndAdd
\n{0}\n{1}", r1, r2));
}

[Test]
public void TestInitializeAndConfigure_Fails()
{
ObjectFactory.Initialize(init =>
{

init.For<IResource>().Singleton().Use<TheFirstResource>();
});

ObjectFactory.Configure(init =>
{

init.For<IResource>().Singleton().Add<TheSecondResource>().Named("test");
});

IResource r1 = ObjectFactory.GetInstance<IResource>();
IResource r2 =
ObjectFactory.GetNamedInstance<IResource>("test");


Console.WriteLine(string.Format("TestInitializeAndConfigure_Fails
\n{0}\n{1}", r1, r2));
}
}

output:

TestUse_Fails
Smtesting.TheSecondResource
Smtesting.TheSecondResource

TestUseOrderChanged
Smtesting.TheFirstResource
Smtesting.TheSecondResource

TestInitializeAndConfigure_Fails
Smtesting.TheSecondResource
Smtesting.TheSecondResource

TestUseAndAdd
Smtesting.TheFirstResource
Smtesting.TheSecondResource

stig

unread,
Sep 23, 2011, 5:19:19 AM9/23/11
to structuremap-users

Matt Jackson

unread,
Sep 22, 2011, 4:56:07 AM9/22/11
to structuremap-users
From my experience, you should only call Use() once per type, as it
specifies the default instance.

Any extra objects that you register for the same type should be
registered via Add().

I don't *think* the fact that they are named/unnamed makes a
difference.
Reply all
Reply to author
Forward
0 new messages