Domanda

This question was probably asked hundreds of times but again: is there a concept of class loaders in .NET. And let me elaborate the problem: I wan’t to inject a class with several additional code items required for being able to plug objects of this class in a framework to be developed.

In Java I do that with a class loader that reads the byte code, apply the necessary modifications and provides the class as a type instance to the application. Now, objects can be created by the way of reflection.

This is for sure possible in .NET also, by the way of reflection. So, using Type::GetType() invokes the TypeResolver of the current AppDomain instance. Within the resolver, the original type is loaded which is then used as the base class of derived type created in a dynamic assembly. It's a bit tricky because the derived types are not in the same assembly, so internal classes are not straightforward to handle. But it's doable and stable.

And now, call me a pedantic German, I have the original type and the derived type loaded whereas in Java I just have the modified type. Will I be able to make this work in .NET as well?

È stato utile?

Soluzione

In order to do some house-keeping here is what went on with the issue.

In fact I despised the approach of changing existing classes upon loading. From the perspective of .NET a DynamicMethod with the owner set to the type being extended would do the trick. However, you’re not able to add data object this way – if that’s a requirement, you need to derive your own class by Reflection.TypeBuilder. Both concepts are not available in .Net Standard (the former PCL).

I strongly suggest you get in touch with the DLR (Dynamic Meta Objects) in the case you have similar requirements – that’s the concept I finally started using.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top