Search code examples
c#lazy-initialization

Why is Lazy<T> not being lazy?


I have several simple database queries using Entity Framework that I would like to load once using Lazy<T> but I can see that the query is executed every time the property is called. Variations I have tried are:

public static IEnumerable<string> Foos => new Lazy<IEnumerable<string>>(() => _db.Foos.Select(x => x.Name)).Value;

public static IEnumerable<string> Foos=> new Lazy<IEnumerable<string>>(() => _db.Foos.Select(x => x.Name).ToArray()).Value;

public static Lazy<IEnumerable<string>> Foos => new Lazy<IEnumerable<string>>(() => _db.Foos.Select(x => x.Name).ToArray());

public static IEnumerable<string> LightingEnvironments
{
    get
    {
        var lazy = new Lazy<IEnumerable<string>>(() => _db.Foos.Select(x => x.Name).ToArray());
        return lazy.Value;
    }
}

Solution

  • You're constructing a new Lazy each time you call the property getter. A Lazy only allows you to re-use an already constructed value if you keep the Lazy instance around and call the Value property on the same Lazy instance each time you need the value.