Home > Enterprise >  Why does an eager-loading lazy-loader throw an error?
Why does an eager-loading lazy-loader throw an error?

Time:04-05

We've got the following code, where, unless we force the lazy-loader to stop being lazy, it'll throw an

System.MissingMemberException: 'The lazily-initialized type does not have a public, parameterless constructor.'

exception. At least, for the case where we already have the value and we're just making the lazy-loader regurgitate it.

My question is - why? Why is this happening, and what can I do so that we don't need to include var _ = _lazyChild.Value;?

public class MyContainedClass
{
    private readonly int _id;

    public MyContainedClass(int id) => _id = id;
}

public class MyContainer
{
    private readonly Lazy<MyContainedClass> _lazyChild;

    public MyContainer(MyRepository repo, int? childId, MyContainedClass child = null)
    {
        ChildId = childId;
        if (childId != null)
        {
            _lazyChild = new Lazy<MyContainedClass>(() => child);
            //Without the below line, later accessing _lazyAnswerGroup will throw:
            //System.MissingMemberException: 'The lazily-initialized type does not have a public, parameterless constructor.'
            var _ = _lazyChild.Value;
        }
        else
        {
            _lazyChild = new Lazy<MyContainedClass>(() => ChildId.HasValue ? repo.Get(ChildId.Value) : null);
        };
    }

    public int? ChildId { get; set; }

    public MyContainedClass Child => _lazyChild.Value;
}

Sidenote - yes I'm aware there's a bug where you pass in an child element and then later change the ChildId. I'm assuming that's unrelated.

CodePudding user response:

I think I've figured it out. We're also calling a method that uses reflection to make a deep-copy of the object in memory. Obviously, that isn't going to call the non-parameterless constructor, and therefore the Lazy<>s aren't being initialized correctly.

  • Related