Handling circular dependencies in Swiz Framework

Swiz is an amazing framework. I was playing around with it this weekend converting a simple Cairngorm project. Swiz handled all autowiring without any problems, until I had to access autowired bean from getter of another autowired bean, that's where I ran into the notorious TypeError: Error #1009: Cannot access a property or method of a null object reference. The problem is that in this case there is no way that Swiz could know that injected property is using another autowired bean in its getter. Note that I was using version 0.6.4-flex3, in latter versions this issue can be fixed or better work around found.

Here are snippets from my classes:

When swiz autowires beans in BeanLoader, LoginPresentationModel comes before ApplicationModel, and when it tries to set up binding between LoginPresentationModel.languageToTranslate and ApplicationModel.languageToTranslate flex throws NPE, as a result of ApplicationModel.so being null at this point. If ApplicationModel came first in the list of candidates for autowiring then I wouldn't get this NPE.

There are couple solutions for this problem:

The first one is to add a condition to the property getter that returns some default value if "so" is null. That would leave the binding to be created.

This solution just doesn't look right.

Another way, which I'm using at least for now, is to manually specify the bean to inject.

In Beans.mxml

You can also implement IInitializingBean and let the controller initialize SO persisted data in the IInitializingBean initialize method.
It will be called after dependencies have been injected. This is much cleaner anyway and keeps the model lightweight.

Comment

1 Response to “Handling circular dependencies in Swiz Framework”


  1. 1 Sönke Rohde

    You could change your presentation models to Prototypes. Then they will only be created when the view is created. At this point in time the autowiring is complete which fixes the “to early” access.

Leave a Reply