开发者

StructureMap stub injection

开发者 https://www.devze.com 2023-04-05 00:20 出处:网络
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:

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:

  1. After the container has been initialized to use the regular implementation - it returns the regular implementation -> Ok.
  2. After injecting the fake implementation -> it returns the fake implementation -> Ok.
  3. 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?

0

精彩评论

暂无评论...
验证码 换一张
取 消