I'm using StructureMap and trying to register a temporary implementation for an interface (a stub).
After reading this article I came up with the following setup:
The definition of the interface:
public interface IConsoleWriter
{
void Write(string message);
}
The regular implementation:
public class ConsoleWriter : IConsoleWriter
{
public void Write(string message)
{
Console.WriteLine("That's the message: '{0}'", message);
}
}
The fake implementation:
public class FakeConsoleWriter : IConsoleWriter
{
public void Write(string message)
{
Console.WriteLine("That's a fake writer who does not care about your message.");
}
}
Now, having all these defined, I use the following scenario:
static void TestTemporaryStub()
{
// register the regular implementation as default
ObjectFactory.Initialize(x => x.For<IConsoleWriter>().Use<ConsoleWriter>());
var writer1 = ObjectFactory.GetInstance<IConsoleWriter>();
writer1.Write("abc");
// temporarily inject a fake implementation
ObjectFactory.Inject(typeof(IConsoleWriter), new FakeConsoleWriter());
var writer2 = ObjectFactory.GetInstance<IConsoleWriter>();
writer2.Write("abc");
// attempt to reset the settings to default
ObjectFactory.ResetDefaults();
var writer3 = ObjectFactory.GetInstance<IConsoleWriter>();
writer3.Write("abc");
}
In the code above, I ask the StructureMap container to retrieve an IConsoleWriter imnplementation three times:
- After the container has been initialized to use the regular implementation - it returns the regular implementation -> Ok.
- After injecting the fake implementation -> it returns the fake implementation -> Ok.
- After reverting back to the defaults -> should return the regular im开发者_Python百科plementation (ConsoleWriter), but it still returns the fake -> Not Ok.
Am I missing something in here?
精彩评论