0

Sample code:

public interface IMyClass
{
    string Name { get; set; }
}

public class MyClass : IMyClass
{
    public string Name { get; set; }
}

public static class Program
{
    public static void Main()
    {
        var container = new Container();

        var class1 = new MyClass() {Name = "class 1"};
        container.Configure(x => x.For<IMyClass>().Use(class1).Named("MyClass"));

        var instance1 = container.TryGetInstance<IMyClass>("MyClass");

        container.EjectAllInstancesOf<IMyClass>();

        var class2 = new MyClass() { Name = "class 2" };

        container.Configure(x => x.For<IMyClass>().Use(class2).Named("MyClass"));

        var instance2 = container.TryGetInstance<IMyClass>("MyClass");

        Console.ReadKey();
    }
}

I would expect instance2 to return class2, but however it returns class1. Anything wrong with the sample code? What I need to do to get class2 instead?

  • I have tested your code in my laptop. I have removed this line `container.EjectAllInstancesOf();`. It gives me an instance of class2. – Krishnraj Rana Apr 14 '15 at 15:59
  • This is not what I get. Even I remove that call, I still get class1. Which version of StructureMap are you using? I am using 3.1.0.0. Thx! – Michael Pi Apr 14 '15 at 21:08
  • According to the (ever so outdated) [docs](http://docs.structuremap.net/ChangingConfigurationAtRuntime.htm#section4) `EjectAllInstancesOf` only ejects singleton instances – PHeiberg Apr 16 '15 at 07:01

1 Answers1

0

This works on SM v2.6.3 (returns class 2). On SM v3.1.1 it is not working as expected (returns class 1). Looks like this is a bug, probably indroduced while refactoring in that area for version 3.0. Looking at container metadata registration before and after calling:

container.EjectAllInstancesOf<IMyClass>();

registrations are cleared but somehow old instance is resolved. Caching issue for singletons probably. It is the same case no matter whether it is named instance or not.

Regarding EjectAllInstancesOf, IMyClass is registered with instances thus it is seen by the container as singleton so it makes sense of using this method.

Just debugged through the code with sources for v3.1.4 and it is working as expected so I advise you to get the latest version from nuget and this should work.

LetMeCodeThis
  • 591
  • 6
  • 10
  • It appears to be that unnamed instance works in SM 3.1.0.0, but not named instance based on my testing. I have just tried on the latest version, SM 3.1.5.154, both named and unnamed work as expected. Thanks! – Michael Pi Apr 20 '15 at 16:07