mercredi 19 juin 2019

Get an attribute for a class containing a property with a Lazy initializtion

I don't think what I'm trying to do is possible. I have a property that is lazy initialized. Within the constructor I want to get the value of an attribute on the class that contains the property. I have a minimal example below.

public class Demo
{
    private Lazy<InternalDemo> data;

    public Demo(*stuff*)
    {
        data = new Lazy<InternalDemo>(*stuff*);
    }

    public string GetDetails()
    {
        return data.Value.Details;
    }

    private class InternalDemo
    {
        public string Details { get; set; }
        public InternalDemo()
        {
            //Details = SomeAttribute.Text -> "Here are details"
        }
    }
}

[SomeAttribute("Here are details")]
public static class DemoContainer
{
    public static Demo Things { get; } = new Demo();
}

//Value is referenced via 
DemoContainer.Demo.GetDetails()

When this is not Lazy, I can use reflection to walk the stack until it finds the class with SomeAttribute defined, however with Lazy, DemoContainer isn't part of the stack.

I know that I could pass in the type of DemoContainer, or ever the value of SomeAttribute to the Demo constructor, but the purpose of this attribute was to avoid having to do so. The properties are static because they're part of a caching mechanism, but I didn't want to initialize them until they're actually used.

Also, I don't want to add reflection outside of the Lazy because there are lots of these static properties and I don't want a large overhead on initial load. I've already tested this.

I suspect I'll end up passing the attribute data as a string to the constructor, but I wanted to make sure there wasn't something else I could do to make this lookup work. It doesn't matter if it's an inefficient way to do it, either, since it will only run on first use.





Aucun commentaire:

Enregistrer un commentaire