Search code examples
spring.net

Spring: Remove singleton


I am unit testing a class that calls

ContextRegistry.GetContext().GetObject("ISomething")

and it's ok if an ISomething isn't defined. So I am trying to test it both ways. Since this definition normally comes from the app.config file and I don't want to edit that file between tests, I'm using [TestFixtureSetUp] and [TestFixtureTearDown] to register the singleton, test, and then I'd like to 'un'-register it. This registers it just fine:

...ObjectFactory.RegisterSingleton("ISomething", new SomethingMOCK());

and I can check to see if it is there:

if (...ObjectFactory.ContainsSingleton("ISomething"))

but I can't seem to REMOVE the singleton I registered. I tried using null:

...ObjectFactory.RegisterSingleton("ISomething", null);

but this throws. Is there a better way?


Solution

  • As far as I know, no such feature exists. It would be tricky, anyway. What should be the semantics if the singleton has been wired to other objects already, before it is removed eventually? Re-setting object properties to null might not be possible as you cannot assume that null is allowed for the affected properties. If the object is wired via constructor injection, there might not even be a setter method.