tags:

views:

293

answers:

2

hi

I'm new on spring.net, and I'm tring to create an List<> of objects. The list is initialized by a loop that calls:

  • IObj obj= (IObj)ContextRegistry.GetContext().GetObject("obj")

  • change object properties....

  • add it to the list...

the problem is : I keep getting the same object every step of the loop so I get a list of the same object

+3  A: 

If your object definitions are not singletons, then you will get a new object each time. Note, by default, singleton is set to true, so you have to explicitly set it to false.

For example, if you are using xml files to configure your objects, set the singleton attribute to false:

<object name="name" type="..." singleton="false"/>
Nader Shirazie
+1  A: 

It is not clear what you are trying to achieve by looping over the "GetObject("obj")" method. Maybe you can post the loop-code?

What "GetObject("obj")" does is to ask the Container for the Object with the name "obj". You stated that want to change the object's properties and add it to a list. This is something the container can do for you: Set the properties of an Object: http://www.springframework.net/doc-latest/reference/html/objects.html#objects-simple-values Create a list: http://www.springframework.net/doc-latest/reference/html/objects.html#objects-collections-values

This list can be injected into an Object you choose.

If you just want non-singleton objects of your IObj, naders answer is correct. Spring calls these non-singleton objects "prototypes". An overview of available Scopes can be found here: http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-scopes

tobsen
Good point. The end result may well be something the container can provide. The only caution here would be to avoid making things more complicated than they should be. Sometimes, just because the container *can* do something, doesn't mean you should use it. It may well be simpler to do the loop+modify+add in code, and just because its code, and not spring xml doesn't make it a bad thing.But this is all dependent on what the end goal is -- and now I'm curious...
Nader Shirazie