LazyLoading - OnLoaded Fire Sequence

Topics: Customizing Orchard, General, Writing modules
Jun 8, 2011 at 12:11 AM

I just ran into something that confused me. I based these off the docs, so hopefully they're following convention.  Say I have a content part called MyPart that has a lazy-loaded property called MyLazyProp defined as such: 

private readonly LazyField<SomeType> _myLazyProp = new LazyField<SomeType>();
public LazyField<SomeType> MyLazyProp { get { return _myLazyProp; } }

Now, in my handler, I put an event handler for OnLoaded<MyPart> that loads in the lazy field.

In my driver, I'm overriding the get/post for the editor like this:

//GET
protected override DriverResult Editor(MyPart part, dynamic shapeHelper) { 
   //...
}

//POST
protected override DriverResult Editor(MyPart part, IUpdateModel updater, dynamic shapeHelper) {
   //...
}
Basically, the lazy property gets properly injected/loaded in the GET method, but not in the POST method.  Am I doing something wrong?

Jun 8, 2011 at 10:58 AM

I had a bit of a dig around DefaultContentManager and the driver/handler code to see what's going on. I think this has something to do with the following code, from the Get(id,options) method of DefaultContentManager:

            // when draft is required and latest is published a new version is appended 
            if (options.IsDraftRequired && versionRecord.Published) {
                return BuildNewVersion(context.ContentItem);
            }
Now, in AdminController's Edit (GET) action, the content item is loaded like this:

            var contentItem = _contentManager.Get(id, VersionOptions.Latest);

Whereas in the EditPOST action which handles the update, we see this instead:

            var contentItem = _contentManager.Get(id, VersionOptions.DraftRequired);

So; on the POST, the item is still being loaded from the database and your OnLoaded handler will run. But then a new version of the item is built to be saved as the latest version record. Consequently the OnLoaded handler won't get run for this version, because it's brand new - not loaded from the database.

I think you need to try Active or Initialize events instead, since they'll get run in either circumstance.