nHibernate loads my first object which have a OneToMany reference to a second object. Using lazy mode, the referenced object is not initialized, only a proxy exists in memory. nHibernate automatically loads the second object in memory when it is accessed.
The question is: when the first object can register for the second object's events? How can I subscribe to the second object's events?
I don't want to break the lazy mode mechanism. For the moment I use a method 'Initialize' I developed myself and which is called from get accessor. Is there a better way to do so?
Can I use IPersistentCollection.AfterInitialize ?
Code:
[Class]
public class CalendarDate
{
private GenericSettings genericSettings;
[ManyToOne(ClassType = typeof(GenericSettings), Cascade = CascadeStyle.AllDeleteOrphan, Column = "generic_settings_id")]
public virtual GenericSettings GenericSettings
{
get
{
Initialize(ref this.genericSettings, OnObjectChanged);
return this.genericSettings;
}
private set { this.genericSettings = value; }
}
public virtual void OnObjectChanged(object sender, NotifyObjectChangeEventArgs e)
{
}
public static void Initialize<T>(ref T obj, NotifyObjectChangedEventHandler objectChanged)
where T : INotifyObjectChanged, new()
{
if (obj == null)
{
obj = new T();
obj.ObjectChanged += objectChanged;
}
else
{
if (!NHibernateUtil.IsInitialized(obj))
{
NHibernateUtil.Initialize(obj);
obj.ObjectChanged += objectChanged;
}
}
}
}
For information, my code is much more complicated for subscribing to events from a list having add/remove events.