I've got a base class for all my custom entity collections, a simple version of it is this:
[Serializable]
public class CollectionBase<T> : List<T> where T : IEntity
{
public bool IsDirty {get;}
public new void Add(T item)
{
this.SetDirty();
base.Add(item);
item.MadeDirty += new EventHandler(item_MadeDirty);
}
// Other standard list methods overridden here
...
public void SetDirty() { } // Mark the collection as dirty
private void item_MadeDirty(object sender, EventArgs e)
{
this.SetDirty();
}
}
The collections sit within a serialized class that sits in Session
(i.e. Customer class in session has a collection of Order entities). The problem is that my entity base class's MadeDirty event is as follows:
[field: NonSerialized()]
public event EventHandler MadeDirty;
Unfortunately, I cannot just remove the NonSerialized
attribute on the event, because this causes issues in the session state server when deployed to my application server.
Is there any way that I can capture a deserialized completion event on the CollectionBase so I can iterate through all the items and re-assign the MadeDirty
event on each deserialization from the Session? I.e.
private void OnDeserialized(object sender, EventArgs e)
{
foreach (T item in this)
{
item.MadeDirty+= 开发者_运维问答new EventHandler(item_MadeDirty);
}
}
But, I can't imagine this is the first time anyone's come across this issue, so is there a better alternative?
Yes, you can add a method with a special attribute and the right signature to your class:
[OnDeserializedAttribute()]
private void RunThisMethod(StreamingContext context)
{
// post-serialize your class
}
Try http://msdn.microsoft.com/en-us/library/system.runtime.serialization.onserializingattribute.aspx and the equivalent OnDeserializedAttribute
精彩评论