PDA

View Full Version : Intantiate Object on Event


jscadden
12-01-2004, 04:40 PM
Is there a way with Spring.net to have the Container instantiate an object off of an event.

Example:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="objects" type="Spring.Context.Support.ApplicationContextHandler,S pring.Context"/>
</configSections>

<objects>
<object name="Application"
class="PMTS.Spring.SpringLauncher, PMTS" />

<object name="PMTS.Spring.SpringController"
class="PMTS.Spring.SpringController, PMTS">
<listener event="Startup" method="OnStartup">
<ref object="Application"/>
</listener>
</object>
</objects>
</configuration>

I want the SpringController to be instantiated when the Startup event is fired by PMTS.Spring.SpringLauncher. Currently it is being instantiated when the following is called.

IApplicationContext ctx = ConfigurationSettings.GetConfig ("objects") as IApplicationContext;

The thinking is have a small footprint when the application is started. and then as the user activates features (By an event firing), those objects are instantiated.[/code]

Mark Pollack
12-02-2004, 11:31 PM
Hi,

The event wiring does not support that usage. Instances of objects are needed to perform the event registration - just as you would have done in code.

One way to potentially do what you want is to have the controller be a lightweight object responsible for creating another objects as identified by the event it receives

For example, if the events were fired by a menu, a controller could listen to these events and then in turn access the ApplicationContext and create the appropriate object on demand - such as an "About Box". The controller could implement IApplicationContextAware (http://www.springframework.net/doc/api/Spring.Context.IApplicationContextAware.html) to get a reference to the application context in order to create and configure an object on demand.

I haven't thought it through but the controller would be configured in some manner with a mapping of event type and corresponding object type (or spring object name) to create. There are probably other means to make this type of dispatching association. Via access to the ApplicationContext, the controller would then create the appropriate object and populate the dependencies. It is probably useful to to specify these objects created on demand as prototype instances, i.e. singleton="false" or with lazy-init="true" for singleton usage.

The IoC approach is the least invasive when the objects in the application can all be created at application startup - this is often the case in server apps but not UI apps. We are just starting to investigate some supporting infrastructure classes for creating UI apps, in particular the easy wiring together of components via events like you are doing. I'd be interested to hear how you are using Spring.NET in more detail to better meet your needs.

Hope this helps.

Cheers,
Mark