using System.Runtime.Serialization;
namespace Project.Silverlight.Helpers
{
public class PartialRehydrator<T>
{
public void Rehydrate(T source, T target)
{
// loop through each property of the given type
foreach (var prop in typeof(T).GetProperties())
{
// look for the DataMemberAttribute on this property
var dma = prop.GetCustomAttributes(typeof(DataMemberAttribute), true);
// if it has a "DMA" then it's in scope for hydration
if (dma != null && dma.Length > 0)
{
// get the value from the source
var sourceValue = prop.GetGetMethod().Invoke(source, null);
// copy the value to the target
prop.GetSetMethod().Invoke(target, new object[] { sourceValue });
}
}
}
}
}
- Published on
Partially re-hydrating a class instance
- Authors
- Name
- Craig Wardman
I was working with some legacy Silverlight code, to add the functionality of saving the current state to a file and re-opening it later.
The way that I chose to implement this was simply using the DataContractSerializer to turn the viewmodel state into a string and write it to a file. I marked the viewmodels with the DataContract attribute and marked any user related properties as DataMember.
This worked great for saving the state to a file, and to some extent it worked when re-hyrating the state back to a viewmodel instance. However the problem I had, is that the viewmodel instances that are created when the application is initialised are part of a web of events registrations and dependancies between other viewmodels in the app.
It was going to be a pain to re-wire the newly hydrated instances into all the places where the "initialised" viewmodels already were. So my solution was to simply "partially re-hydrate" the already existing viewmodel instances.
To acheive this with minimal on-going maintenance, I wrote a simple generic class that uses reflection to identify all the DataMember properties of a class and copies the values from one instance to another. I could then re-hydrate an instance from the file and from that partially rehydrate the plumbed in existing instance.
Class below: