Lazy Initialization for data access
I'm accessing database to bulk populate fields.
PopulateAobjs();
PopulateBobjs();
PopulateCobjs();
.开发者_开发百科..
Once the values are populated, I store the entities in a Dictionary<Id, Entity>
.
I'd like to make this process lazy, in such a way that, if I don't need C
objects then I don't need to call that method. etc.
How can this be done?
LazyInit<>?
Rather than doing such initialization routines, you'd rather use lazy loading properties for such things.
private Lazy<IEnumerable<CObject>> cObjects = new Lazy<IEnumerable<CObject>>(LoadCObjects);
public IEnumerable<CObject> CObjects
{
get { return this.cObjects.Value; }
}
CObjects
will then be loaded the first time anyone accesses the property.
EDIT: When you're not in .NET 4.0, Lazy<T>
is just a fancy way for something like that:
private IEnumerable<CObject> cObjects;
public IEnumerable<CObject> CObjects
{
get
{
if (this.cObjects == null)
lock (this.someLockObject)
if (this.cObjects == null)
this.cObjects = this.LoadCObjects();
return this.cObjects;
}
}
To do that, I usually have the code that loads the collection in the property get method. Depending on the class, it will either load the data directly or request that the global cache load the data.
Property FooCustomers
Get
If _Customers IS NULL THEN Then _Customers = CustomerCache.FindByKey(companyKeys)
Return _Customers
精彩评论