I'm not so sure about the similar code in .NET but I'm interested in .NET Standard or .NET Core, my custom CustomTypeDescriptor never has a chance to be injected/used because the custom TypeDescriptionProvider does not seem to work, here is a simple implementation (actually not any custom logic added yet):
public class CustomTypeDescProvider : TypeDescriptionProvider
{
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
{
//set breakpoint here and wait forever for its jumping in.
return base.GetTypeDescriptor(objectType, instance);
}
}
I've tried adding the custom description provider like this:
public class MyType {
static MyType(){
TypeDescriptor.AddProvider(new CustomTypeDescProvider(), typeof(MyType));
}
//...
}
as well as using the TypeDescriptionProviderAttribute like this:
[TypeDescriptionProvider(typeof(CustomTypeDescProvider))]
public class MyType {
//...
}
It never comes to my set breakpoint inside GetTypeDescriptor(Type objectType, object instance). So with my knowledge, it should be invoked at least when any code accessing the metadata info (attributes, properties, ... such as by using reflection) of the type MyType, but it always seems to use the default provider.
Not any exception raised to tell me that Hey your code will not work, stop hoping for it working, and actually I can even see this event TypeDescriptor.Refreshed triggered after the call TypeDescriptor.AddProvider, which as documented means that it succeeded, well really ridiculous, maybe I don't understand its definition of the so-called success.
Why is it not working in this case? Don't we have any way to make it work? This is especially important to me to make my library project not depend on some dependencies.
Update
I expect my code should run and provide custom metadata info (such as attributes) when using reflection like this:
var attrs = typeof(MyType).GetCustomAttributes();
However I've just realized that looks like the TypeDescriptor provides another storage of metadata which can only be accessed via the TypeDescriptor (not via reflection), like this:
var attrs = TypeDescriptor.GetAttributes(typeof(MyType));
Well if so it's just useless =)) , we know that Reflection is some kind of a very popular way to extract metadata, providing a standard API to access metadata, all libraries will use reflection, so we need some magic to inject into the reflection's flow, not into the TypeDescriptor's flow. Really it's confusing me, I really thought that TypeDescriptor is some powerful tool having a strong association with reflection, but looks like it's just another very different thing.