I have a cart model class that has a List property like so:
public List<CartItem> CartItems
{
get
{
if (_cartItems == null)
_cartItems = Services.CartItemService.GetCartItems();
return _cartItems;
}
}
private List<CartItem> _cartItems;
This is fine, unless the service that’s used to query the data from SQL Server returns null, in which case, the database can be unnecessarily hit multiple times as CartItems is referenced. I then noticed that Lazy<T> was available to me, so I attempted to modify my code slightly (since Lazy<T> accounts for null and would prevent multiple hits to the database)
public List<CartItem> CartItems
{
get
{
return _cartItems.Value;
}
}
private Lazy<List<CartItem>> _cartItems = new Lazy<List<CartItem>>(() =>
{
// return Services.CartItemService.GetCartItems(); cannot be called here :(
});
The compile time error is
“A field initializer cannot reference the non-static field, method, or
property”
Services is a public property in the same class as CartItems but I can’t figure out if it’s even possible to access that in a Func<List<CartItem>> delegate. I do not want to have to create factory classes for each property – I have to us something like this in many places, and I want to be … well…. lazy.
You can create the field in a constructor.
It might also pay to move the service call to it’s own method.
I.e.