vendredi 17 mai 2019

Looking for some best practices regarding reflection

I am currently my very own cute microkernel because all of then out there don't satisfy my needs (too focused on like IOC, or too fat). Thus I am heavily into reflection at the moment, like calling constructors of custom attributes with custom parameters on classes that a user of my microkernel might have invented someday in the future.

The microkernel is part of a larger framework that also focuses on heavy parallelization. Which means that the microkernel will be quite busy creating and administering and deleting tons of small objects which might have lots of (intended) depencencies (the objects, not the classes), think NN, think AI. (I am currently thinking Microsoft's embracement on TensorFlow, on TensorCores...)

What can I say? It works, so far. Will need some input on ducktyping later, but for now, I am in Need for Speed^^

Look at this piece of code... You don't need to understand the underlying stuff, just as a hint of the complexity...

    static void ApplyPropertyPostAttributes(dynamic entity, PropertyInfo[] properties)
    {
        foreach (var prop in properties)
        {
            var pcas = prop.CustomAttributes.ToList();

            foreach (var ca in pcas)
            {
                var acac = ca.Constructor;
                var acas = ca.ConstructorArguments;
                var args = new List<object>();
                foreach (var aca in acas)
                {
                    args.Add(aca.Value);
                }

                var attr = acac.Invoke(args.ToArray());
                var mi = attr.GetType().GetMethod(@"ModifyPropertyValue");
                if (mi != null)
                {
                    mi.Invoke(attr, new[] { entity, prop, null });
                }
            }
        }
    }

This piece of code, as you already might have noticed, is a part of the IOC/DI stuff of my microkernel. It looks for certain attributes applied to the formerly created class, creates instances of the attributes, then creates an instance the the attribute, then calls the ModifyPropertyValue method of the attribute to do the actual injection. The implementation of the attribute is pretty simple and sleek.

So far I am pretty happy and even kind of proud of myself to have managed to have this piece work.

Of course stability and reliability are always the number one concerns. But if you have some hints, tips, ideas to make it faster, not just this very part of code, but like "when using reflection, you should alwasy... and never... and read this!", I will be very thankful!

Enjoy the weekend, folks. Kindest regards from sunny Germany,

Carsten





Aucun commentaire:

Enregistrer un commentaire