OnCreated not called when created

I’m using Microsoft .NET RIA Services to build a Silverlight application, and today I had a bug.  At first it looked like the DataGrid’s RowDetailsTemplate wasn’t working, but that wasn’t it.

After debugging it for a little while I realized that the property I had data bound to, “FullName” wasn’t being set by the OnCreated() method,  which is a partial method called by the class’s constructor.

Apparently .NET RIA Services is using reflection in  such a way that it doesn’t call the constructor when it is creating client side objects from a server response.  This is possible using the serialization method: FormatterServices.GetUninitializedObject().  So when .NET RIA Services is de-serializing objects from the server it doesn’t call the constructor and the objects are created without their OnCreated() method being called.

In my case, the solution was simply to move the initialization of the derived  FullName property into the property getter rather than in OnCreated() method.  Then I had to implement the appropriate partial methods for the “FirstName”, “LastName” “SpouseFirstName” and “SpouseLastName”properties so that they would raise the property changed event for the “FullName” property.

Nice and easy, however it’s still a shame there’s no way for an object to know when it has been newly retrieved from the server.

Leave a Reply

Your email address will not be published. Required fields are marked *