views:

56

answers:

2

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<>?

+2  A: 

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;
    }
}
herzmeister der welten
only i m not on .net 4. so i should look at LazyInit<>?
Updated the answer. You might be able to use `LazyInit<>` too, it should work similar to the `Lazy<>` example.
herzmeister der welten
thanks man.....
A: 

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
Jonathan Allen