PDA

View Full Version : runtime argument for constructor. help?


FallenHammer
09-01-2006, 05:07 PM
Hi,
Would anybody please tell me if there is a way to supply runtime argument when injecting object constructor? Let say host object (Host class) creates items (Item class) by using Item(Host arg) constructor. In C# within Host object instance I can do this like

Item i = new Item(this);

Can I do something like this by querying Item from context and supplying runtime object as constructor argument (how about multiple arguments)?

Thanks in advance.

Bruno Baia
09-01-2006, 11:57 PM
Hi,

A solution is to change the object definition at runtime before to get the object from context :


<object id="MyItem" type="MyNamespace.ItemObject, MyAssembly" lazy-init="true"/>



IApplicationContext ctx = ContextRegistry.GetContext();

IObjectDefinition objectDefinition = ctx.GetObjectDefinition("MyItem");
objectDefinition.ConstructorArgumentValues.AddInde xedArgumentValue(0, new HostObject());

ItemObject item = (ItemObject) ctx.GetObject("MyItem");


Hope this help,
Bruno

Erich Eichinger
09-02-2006, 12:28 AM
Hmm. Changing the definition is a global change. You could easily run into concurrency and maintenance problems with that.

Why not simply write somthing like


ItemObject item = (ItemObject) ctx.GetObject("MyItem");
item.Host = this;


?

It's not the most elegant solution. But it's short & simple.

Another way could possibly be to use CallContext.SetData() in your code to set the argument and access this argument via CallContext.GetData() within the definition - or directly in your ItemObject-ctor.

cheers,
Erich

FallenHammer
09-05-2006, 03:28 PM
Erich,
Yes, I did the same first. The problem is that there are many places of using Item like objects in project and they have multi parametrized constructors, so I ended up with coding each of them. :(

Bruno,
The way you are suggesting seems promising. Setting lazy-init and getting items from helper class do not sound a big problem. What caught my attention was Erich's mentioning of possible concurrency problem. What problem may I have there with concurrency?

Thanks

Erich Eichinger
09-05-2006, 07:21 PM
Hi,

I'm not sure, if I fully understand, what you are trying to achieve. Do you need to change the ctor-argument's value each time you obtain a new "Item" instance? Or do you want to set it only once (e.g. at application startup)?

In the first case, you may run into concurrency problems. A definition is global. If you modify it, all subsequent calls to GetItem() will use this definition and therefore the most recent value you supplied as ctor-argument.

In the second case I don't see any problems. You can safely use Bruno's solution. Maybe you may want to checkout other possible methods of injection here (especially usages of interface IFactoryObject):
http://www.springframework.net/doc/reference/html/objects.html#objects-advancedproperty-setting


cheers,
Erich