views:

33

answers:

2

I have an integration test harness where I want to teardown and then re-instantiate some of the singleton-scoped objects I've registered with StructureMap, after and before each test.

This way I can simulate the actual run time environment, but not have the singleton's state being passed from one test to another. Maybe this isn't a great way to do an integration test, but I'm running out of alternative solutions (read open to any advice).

So can an object with InstanceScope.Singleton, be re-instantiated?

What's the best way to do re-instantiate a singleton-scoped object with StructureMap?

+1  A: 

I'm not much of a StructureMap user, but in IoC containers in general, you shouldn't try to do this. Think of a singleton x that depends on another singleton y. Now re-instantiate y. But x would still hold a reference to the old instance of y!

The lifetime of a singleton is supposed to be the same as its container, so if you want to kill an instance of a singleton, you'll have to kill its container. You can scope this by using a nested container.

Mauricio Scheffer
Well, in this situation I think it was acceptable because there were only two to three objects scoped singleton, and non of them touched each other. I solved this problem using nested containers as you suggest here.
Mark Rogers
+1  A: 

ObjectFactory.Initialize will re-initialise the container configuration. Do that in your test setup.

AbstractCode