Persistence Ignorant Lazy Loading for Your Hand-Rolled DAL in .NET 4.0 Using Lazy
This post is a brief update to the .NET 3.5 article I posted about P.I. lazy loading. The only major change I have made to the code is to use the new Lazy<T> class that was introduced in .NET 4.0. This considerably cleans up the LazyLoadingList<T> class from the previous post.
publicclassLazyLoadingList<T>:IList<T>{privateLazy<IList<T>>_lazyList;publicLazyLoadingList(Lazy<IList<T>>lazyList){_lazyList=lazyList;}#region Implementation of IEnumerablepublicIEnumerator<T>GetEnumerator(){return_lazyList.Value.GetEnumerator();}IEnumeratorIEnumerable.GetEnumerator(){return_lazyList.Value.GetEnumerator();}#endregion#region Implementation of ICollection<T>publicvoidAdd(Titem){_lazyList.Value.Add(item);}publicvoidClear(){_lazyList.Value.Clear();}publicboolContains(Titem){return_lazyList.Value.Contains(item);}publicvoidCopyTo(T[]array,intarrayIndex){_lazyList.Value.CopyTo(array,arrayIndex);}publicboolRemove(Titem){return_lazyList.Value.Remove(item);}publicintCount{get{return_lazyList.Value.Count;}}publicboolIsReadOnly{get{return((ICollection<T>)_lazyList.Value).IsReadOnly;}}#endregion#region Implementation of IList<T>publicintIndexOf(Titem){return_lazyList.Value.IndexOf(item);}publicvoidInsert(intindex,Titem){_lazyList.Value.Insert(index,item);}publicvoidRemoveAt(intindex){_lazyList.Value.RemoveAt(index);}publicTthis[intindex]{get{return_lazyList.Value[index];}set{_lazyList.Value[index]=value;}}#endregion}
publicclassCompanyDAO:ICompanyDAO{List<Company>_companiesInDatabase=newList<Company>{newCompany(){Name="ACME"},newCompany(){Name="Hardees"}};#region Implementation of ICompanyDAOpublicCompanyGetByName(stringname){// Write to console to demonstrate when loading is happeningConsole.WriteLine("---Loading Company---");// Pretend we are calling / mapping from a store procedurevarcompany=_companiesInDatabase.Where(x=>x.Name==name).First();// Create / add the lazily loaded collectionif(company!=null){varlazyLoader=newLazy<IList<Employee>>(()=>{varemployeeDAO=newEmployeeDAO();returnemployeeDAO.GetByCompanyName(name).ToList();});company.Employees=newLazyLoadingList<Employee>(lazyLoader);}returncompany;}#endregion}