Virtual Proxy Lazy Loading Strategy
In this sample I’m going to show how to use a pattern called virtual proxy as a lazy loading strategy. There are many times when you want to load a parent object that contains child objects. It is often the case that you don’t want to actually load up those children from the database until they are needed. The virtual proxy pattern will help solve this problem. Basically you create an object that looks like the real object but will delay the loading of that object until it’s needed.
In this sample, a parent order object contains a list of line items. The order object is passed in it’s dependencies; the list of children, into it’s constructor.
{
private IEnumerable<ILineItem> line_items;
public Order(IEnumerable<ILineItem> line_items)
{
this.line_items = line_items;
}
public IEnumerable<ILineItem> LineItems
{
get
{
return this.line_items;
}
}
}
Hanging off the order object there is a property that clients can then call to get the child list of line items. Since we don’t want to explicitly load the children that are to be passed in we can create a virtual proxy that looks and acts like the IEnumerable<ILineItem>.
{
private IEnumerable<ILineItem> line_item_list;
private readonly Func<IEnumerable<ILineItem>> line_item_fetch;
public LineItemVirtualProxy(Func<IEnumerable<ILineItem>> fetch)
{
line_item_fetch = fetch;
}
private IEnumerable<ILineItem> list
{
get
{
if (line_item_list == null)
{
line_item_list = line_item_fetch();
}
return line_item_list;
}
}
public IEnumerator<ILineItem> GetEnumerator()
{
return list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return list.GetEnumerator();
}
}
As you can see this object looks exactly like the IEnumerable<ILineItem> object that the order’s constructor is looking for except for the fact that the actual list does not exist yet. A Func is passed in that will later be executed when the LineItems property off of the order object is called.
In this example, the Func points to a method off of a repository object that will fetch the actual line items as seen below
var order = new Order(proxy);
Similar Posts
- Configure App.config Application Settings During MSI Install
- Team Foundation Server Build Notification Screen
- Using VSDBCMD and MSBUILD to Build and Deploy DBPro Projects
