... or, in other words, ThreadLocalStorageLifecycle overrides UniquePerRequestLifecycle.
For unit testing purposes I wanted to get a new instance of class each time I requested it from
StructureMap's container by name. However despite of life cycle settings, constructor has been called only once. After spending several hours on investigation of what's happened I discovered that UniquePerRequestLifecycle takes effect only when it's specified on a only named instance of that type. If there is at least one instance with ThreadLocalStorageLifecycle - UniquePerRequestLifecycle behavior will be ignored.
public class Test {
public static int InstanceCounter { get; set; }
public Test() {
InstanceCounter++;
}
}
static void Main(string[] args) {
var container = new StructureMap.Container();
container.Configure(config => {
config.For
()
.LifecycleIs(new StructureMap.Pipeline.UniquePerRequestLifecycle())
.Use(() => new Test())
.Named("test");
config.For()
.LifecycleIs(new StructureMap.Pipeline.ThreadLocalStorageLifecycle())
.Use(() => new Test())
.Named("testLocalStorage");
});
Test.InstanceCounter = 0;
var test1 = container.GetInstance("test");
var test2 = container.GetInstance("test");
var test3 = container.GetInstance("test");
Console.WriteLine("Number of instances (expected to be 3): {0}", Test.InstanceCounter);
Console.WriteLine("Press Enter...");
Console.ReadLine();
}
Useful findings: