6 Object Lifecycle

This chapter lists several features that go beyond the configuration features listed in previous chapters.

6.1 Using Factories

Sometimes configuring the target object directly may not be sufficient. Maybe you want to execute some complex logic on object creation that would be difficult to setup declaratively. In these cases you can use a factory instead. The factory is a normal AS3 class that you can configure like any other class in Parsley, using Metadata, MXML or XML tags. The only difference is that one method is marked as a factory method (again using Metadata, MXML or XML):

class CategoryFactory {

    public var categoryName:String;
    
    [Inject]
    public var bookManager:BookManager;
    
    [Factory]
    public function createCategory () : Category {
        var books:Array = bookManager.getBooksForCategory(categoryName);
        return new Category(categoryName, books);
    }
}

You can then use this factory in your configuration, for example in MXML:

<mx:Object 
    xmlns:mx="http://www.adobe.com/2006/mxml"
    xmlns:model="com.bookstore.model.*">
    
    <model:BookManager/>
    
    <model:CategoryFactory id="historyCategory" categoryName="history"/>

    <model:CategoryFactory id="politicsCategory" categoryName="politics"/>

    <model:CategoryFactory id="artsCategory" categoryName="arts"/>
        
</mx:Object> 

Each of the factories we defined above will get the BookManager instance injected and then produce instances of Category.

The special thing about using factories is that under the hood Parsley actually creates two object definitions for each factory: One for the factory itself and one for the type the factory method produces. This means that you can also place metadata tags on the target type (in this case the Category class) if you want the object that the factory produces to send and receive application messages managed by Parsley for example.

This also means that you can use the factory and the objects it creates at injection points, although in most cases you'll be interested in the objects produced by the factory:

[Inject(id="historyCategory")]
public var historyBooks:Category;

It is recommended not to use factory methods with a return type of Object like this:

[Factory]
public function createInstance () : Object {

It would work, Parsley would happily process this kind of factory method. But you'll lose some of Parsley's useful capabilities, since it uses the return type of the method for producing the object definition for the target type. If the target type is just Object, the metadata tags on the objects this factory actually produces would not be processed, since this happens before the factory method will be invoked for the first time. Furthermore you cannot use objects produced by such a factory for Dependency Injection by Type, since the type can only be determined dynamically. You would then be constrained to Injection by Id.

Of course, like with most other Parsley features, you may also declare the factory method in MXML or XML. This may come in handy in some edge cases, for example for a factory that has more than one method that produces objects. In this case placing metadata tags in the class itself would not be possible (only one [Factory] tag is allowed).

MXML Example

<Object id="monkey" type="{ZooFactory}">
    <Factory method="createMonkey"/> 
</Object>
<Object id="polarBear" type="{ZooFactory}">
    <Factory method="createPolarBear"/> 
</Object>

XML Example

<object id="monkey" type="com.example.ZooFactory">
    <factory method="createMonkey"/> 
</object>
<object id="polarBear" type="com.example.ZooFactory">
    <factory method="createPolarBear"/> 
</object>

6.2 Asynchronous Object Initialization

A lot of operations in the Flash Player execute asynchronously. So it might happen that you want an object configured in the Parsley IOC Container to load some data or assets first, before the rest of the Context gets initialized and before this asynchronously initializing object gets injected into other objects. In this cases you can use the [AsyncInit] tag on any EventDispatcher that fires events when the initialization is completed (or if it has failed):

[AsyncInit]
public class FileLoader extends EventDispatcher {

    public var filename:String;

    [Init]
    public function init () : void {
        var loader:URLLoader = new URLLoader();
        loader.addEventListener(Event.COMPLETE, fileLoaded);
        loader.addEventListener(IOErrorEvent.IO_ERROR, handleError);
        loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, handleError);
        loader.load(new URLRequest(filename));            
   }
   
   private function fileLoaded (event:Event) : void {
       // handle loaded file
       dispatchEvent(new Event(Event.COMPLETE));
   }
   
   private function handleError (event:ErrorEvent) : void {
       dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, false, false, event.text));
   }
   
}

In the example above the [AsyncInit] tag tells the framework that this is an asynchronously initializing object. In the method annotated with [Init] which will be invoked after configuration and dependency injection has been processed for that object (see 6.3 Object Lifecycle Methods for details) we start the loading process. Depending on whether the loading succeeds or not we then dispatch either an Event.COMPLETE or an ErrorEvent.ERROR. The container will listen for those two events. In case of Event.COMPLETE it will proceed with Context initialization. In case of ErrorEvent.ERROR the whole Context initialization process will be cancelled.

Switching event types

Event.COMPLETE and ErrorEvent.ERROR are the default event types to signal whether initialization has completed or failed. They can be switched with attributes of the [AsyncInit] tag:

[AsyncInit(completeEvent="myCustomCompleteEvent",errorEvent="myCustomErrorEvent")]

Initialization order

In case you want to explicitly specify the initialization order you can do that with the order attribute:

MXML Example

<Object id="welcomeText" type="{FileLoader}" order="1">
    <AsyncInit/>
    <Init method="init"/>
    <Property name="filename" value="welcome.txt"/>
</Object>

XML Example

<object id="welcomeText" type="com.example.FileLoader" order="1">
    <async-init/>
    <init method="init"/>
    <property name="filename" value="welcome.txt"/>
</object>

The default value if you omit this attribute is int.MAX_VALUE so that all objects without an order attribute will execute last and in arbitrary order. The attribute can be set to any positive or negative integer value. The order attribute can also be used for objects that initialize synchronously.

6.3 Object Lifecycle Methods

If you want the Parsley Container to invoke methods on your object when it is created or when it is destroyed, you can add the [Init] or [Destroy] metadata tags to the corresponding methods:

[Init]
public function init () : void {
    [...]
}
[Destroy]
public function dispose () : void {
    [...]
}

The methods marked with [Init] get invoked after the object has been instantiated and all injections have been processed.

The methods marked with [Destroy] get invoked after the Context instance they belong to has been destroyed with Context.destroy() or when the object was removed from the Context. See 6.3 Object Lifecycle Methods for details.

For Flex Components declared in regular MXML files and wired to the Context as described in 7 Dynamic View Wiring the lifecycle is different: For those objects the methods get invoked whenever the object is added to or removed from the stage respectively. Of course the [Destroy] method additionally gets invoked if the Context the object was wired to was destroyed.

6.4 Dynamic Objects

Since version 2.1 there is a new interface DynamicContext. Such a Context allows you to dynamically add and remove objects from the Context. In most cases this is not intended to be used by normal application code, but you can easily build extensions on top of that functionality that require some more flexibility than the regular Context. Internally the DynamicContext will be used for wiring views which are added and removed from the Context depending on the time they are placed on the stage and (starting from version 2.2) for short-lived Command objects which are only added to the Context to perform their asynchronous operation and then immediately get removed again.

Dynamic Objects almost behave the same like regular objects. In particular this means:

There is only one significant restriction for using dynamic objects:

This restriction is natural, since dependency injection comes with validation which would not be possible if the set of objects available for injection could change at any point in time. This is no real limitation anyway since you can get hold of these dynamic objects through their lifecycle methods, in case you want to get notified whenever an object of a particular type enters the Context (or any scope of Contexts).

You can create a dynamic Context from a regular one:

var dynamicContext:DynamicContext = context.createDynamicContext();

This way the dynamic Context is connected to the regular one and all objects living in that Context or one of its parents can be injected into the dynamic objects. You can then simply add any object to that Context:

var instance:Object = ...;
var dynamicObject:DynamicObject = dynamicContext.addObject(instance);

In this case an ObjectDefinition will be created for the existing instance and metadata will be processed for the type of that instance, performing any required dependency injection, message receiver registration or lifecycle method invocation.

The object can be removed from the Context at any point in time:

dynamicObject.remove();

At this point the method marked with [Destroy] will be invoked on that object (if existent) and any message receiver registrations will be terminated. The object is then fully removed from the Context.

For building extensions which talk to a DynamicContext instance from within a ObjectDefinitionDecorator or ObjectDefinitionFactory implementation there are two interesting variants of the addObject method shown above. First it is possible to pass an additional ObjectDefinition to the method:

var definition:ObjectDefinition = ...;
var instance:Object = ...;
var dynamicObject:DynamicObject = dynamicContext.addObject(instance, definition);

In this case the definition will not be created by the dynamic Context like in the preceding example. Instead the specified definition will be used. In version 2.2 this mechanism will be used internally to support the new option to configure dynamically wired views in MXML. An existing instance will have to be configured by an ObjectDefinition then which has been created elsewhere.

Finally you can also just pass a definition to the dynamic Context and it will create a new instance based on that definition:

var definition:ObjectDefinition = ...;
var dynamicObject:DynamicObject = dynamicContext.addDefinition(definition);

The instance created by the Context can then be accessed like this:

var instance:Object = dynamicObject.instance;

In all these different use cases removal of the object happens in the way already demonstrated:

dynamicObject.remove();