Okay my first post and I was going to jump right in and try a fill a gap in the blogging worlds knowledge about having a read only collection that supports notifications of modifications to collection members when programming in .Net - what happens when ReadOnlyCollection<T> meets BindingList<T>?
The simple answer to that question is ReadOnlyObservableCollection<T> in version 3.0 or higher - it provides the exactly functionality I require and gets away from the awful 'Binding' prefix name which has to much association with 'Data Binding' in the MS world. But in version 2.0 you don't have a such a luxury :).
This is really the sub-text of this post and the problem I'm trying to solve - How can I observe events on a domain entities (including collections) when implementing Domain Driven Design in a winforms environment that utilises an MVC(P) pattern?
If you don't know much about Domain Drive Design check the out website and for a great set of posts on see Casey Charlton's blog and accompanying DDD website.
Back to the question, By implementing the interfaces INotifyCollectionChanged and INotifyPropertyChanged we allow the domain entities and value objects to notify anyone who is interested when their state changes. So if we have our entities deriving off a base class that implements INotifyPropertyChanged and a property changs we fire the event PropertyChanged and anyone observing gets notified.
A simple base class that implments INotifyPropertyChanged:
public abstract class Observable : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected void NotifyPropertyChangedObservers(string propertyName)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
And a domain entity that derives from this, finding a quick and easy domain to model is tricky :)
public sealed class Person : Observable
{
private string firstName;
private string lastName;
public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public string FirstName
{
get { return firstName; }
set { SetProperty(ref firstName, value, "FirstName"); }
}
public string LastName
{
get { return lastName; }
set { SetProperty(ref lastName, value, "LastName"); }
}
private void SetProperty(ref T existingValue, T newValue, string propertyName)
{
if (!Object.Equals(newValue, existingValue))
{
existingValue = newValue;
NotifyPropertyChangedObservers(propertyName);
}
}
}
So this mechanism work great, I'm now able to observe any changes to any value type properties on the domain entities - this is really useful in a our Model View Controller Presenter pattern, we can now bind our Model to the View and the View now gets automatically notified of changes to the Model and knows how to handle updating the UI. It should be said we don't couple the Model directly to the View we use a Presenter hence the MVC(P), the Presenter creates a Presentation wrapper around the Model that is bound to the View.
But what about when the properties start to represent more complicated such as collections?
Lets tackle the .Net 3.0 version first- Simple we use the ReadOnlyObservableCollection<T> and we now have the advantage of observing any changes to the entities inside the collection but we don't let anyone change the contents of the collection - you wouldn't want anyone to come along and just add more children to your family without your say so would you :)
public sealed class Family : Observable
{
private Person firstParent;
private Person secondParent;
private ObservableCollection children;
public Family(Person firstParent, Person secondParent, IList children)
{
this.firstParent = firstParent;
this.secondParent = secondParent;
this.children = new ObservableCollection();
foreach (Person child in children)
this.children.Add(child);
}
public Person FirstParent
{
get { return firstParent; }
}
public Person SecondParent
{
get { return secondParent; }
}
public ReadOnlyObservableCollection Children
{
get { return new ReadOnlyObservableCollection(children); }
}
private void SetProperty(ref T existingValue, T newValue, string propertyName)
{
if (!Object.Equals(newValue, existingValue))
{
existingValue = newValue;
NotifyPropertyChangedObservers(propertyName);
}
}
}
Now to do this in .Net 2.0 becomes a bit of an issue we don't have the luxury of ObservableCollection or ReadonlyObservableCollection we have to role our own implementation that some how combines the functionality of ReadOnlyCollection and BindingList. My first attempt was to derive from BindingList and override any method that modifies the list
public sealed class ReadOnlyBindingList : BindingList
{
...
}
But I discovered an important thing I wasn't able to override methods like 'Add', 'Remove' I had to use the 'new' operator which set alarm bells off - this is a code smell if ever I've seen one. This was confirmed when talking to another dev who pointed out this would break Liskov's Subsitution Princple if I were to replace an use of my ReadOnlyBindingList with a normal BindingList. So that attempt fails before getting of the launch pad...
So the answer is to use containment of the BindingList collection and implement the IBindingList interface...
public sealed class ReadOnlyObservableCollection<T> : IBindingList<T> where T : class
{
public event ListChangedEventHandler ListChanged = delegate { };
private BindingList<T> innerList;
public ReadOnlyObservableCollection(IList list)
{
innerList = new BindingList<T>();
foreach (T item in list)
innerList.Add(item);
innerList.ListChanged += HandleListChanged;
}
void IBindingList.AddIndex(PropertyDescriptor property)
{
((IBindingList)innerList).AddIndex(property);
}
public object AddNew()
{
throw new NotImplementedException("ReadOnlyObservableCollection!");
}
public bool AllowEdit
{
get { return true; }
}
public bool AllowNew
{
get { return false; }
}
public bool AllowRemove
{
get { return false; }
}
void IBindingList.ApplySort(PropertyDescriptor property, ListSortDirection direction)
{
((IBindingList)innerList).ApplySort(property, direction);
}
int IBindingList.Find(PropertyDescriptor property, object key)
{
return ((IBindingList)innerList).Find(property, key);
}
bool IBindingList.IsSorted
{
get { return ((IBindingList)innerList).IsSorted; }
}
void IBindingList.RemoveIndex(PropertyDescriptor property)
{
((IBindingList)innerList).RemoveIndex(property);
}
public void RemoveSort()
{
((IBindingList)innerList).RemoveSort();
}
ListSortDirection IBindingList.SortDirection
{
get { return ((IBindingList)innerList).SortDirection; }
}
PropertyDescriptor IBindingList.SortProperty
{
get { return ((IBindingList)innerList).SortProperty; }
}
bool IBindingList.SupportsChangeNotification
{
get { return ((IBindingList)innerList).SupportsChangeNotification; }
}
bool IBindingList.SupportsSearching
{
get { return ((IBindingList)innerList).SupportsSearching; }
}
bool IBindingList.SupportsSorting
{
get { return ((IBindingList)innerList).SupportsSorting; }
}
public int Add(object value)
{
throw new NotImplementedException("ReadOnlyObservableCollection!");
}
public bool Contains(object value)
{
return innerList.Contains(value as T);
}
public int IndexOf(object value)
{
return innerList.IndexOf(value as T);
}
public void Insert(int index, object value)
{
throw new NotImplementedException("ReadOnlyObservableCollection!");
}
public bool IsFixedSize
{
get { return true; }
}
public void Remove(object value)
{
throw new NotImplementedException("ReadOnlyObservableCollection!");
}
public void RemoveAt(int index)
{
throw new NotImplementedException("ReadOnlyObservableCollection!");
}
public object this[int index]
{
get { return innerList[index]; }
set { throw new NotImplementedException("ReadOnlyObservableCollection!"); }
}
public T this[int index]
{
get { return (T)innerList[index]; }
set { throw new NotImplementedException("ReadOnlyObservableCollection!"); }
}
public void CopyTo(Array array, int index)
{
innerList.CopyTo((T[])array, index);
}
bool ICollection.IsSynchronized
{
get { return ((ICollection)innerList).IsSynchronized; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)innerList).SyncRoot; }
}
public bool RaisesItemChangedEvents
{
get { return true; }
}
public void Clear()
{
throw new NotImplementedException("ReadOnlyObservableCollection!");
}
public bool IsReadOnly
{
get { return true; }
}
public int Count
{
get { return innerList.Count; }
}
public System.Collections.IEnumerator GetEnumerator()
{
return innerList.GetEnumerator();
}
private void HandleListChanged(object sender, ListChangedEventArgs args)
{
NotifyListChangedObservers(args);
}
private void NotifyListChangedObservers(ListChangedEventArgs args)
{
ListChanged(this, args);
}
}
So to implement a ReadOnlyObserableCollection collection in .Net 2.0 can be done relatively easily, but it's a no brainer if you're using a newer version of the framework :)
There is one issue relating to providing observable entities in the domain, am I coupling the presentation functionality into the domain entities by doing this?
I don't think this is as black and white as using repositories from domain entities - I don't believe you should use repositories in domain entities. The reason I believe this is because by providing observable entities in the domain doesn't mean they will be used by the presentation nor am I doing this to support any presentation pattern.
Thanks for this info
ReplyDelete