|
Thank you for the feedback about the documentation.
A comment about the “MockAttributesAreApplied” method you have posted. This won’t work with the MetadataType attribute.
You are using reflection ‘GetType()’ to retrieve the attributes attached to the properties. Reflection is the low level object introspection technique provided by the .NET Framework.
TypeDescriptor is similar to reflection but it is the high level technique for introspection. The TypeDescriptor allows introducing new virtual metadata which doesn’t exist on the real .NET object. This feature is used for the MetadataType attribute.
Here is an example which should show the difference:
public interface IPerson
{
[Required]
string Name { get; set; }
}
[MetadataType(typeof(IPerson))]
public class Person : Model, IPerson
{
public string Name { get; set; }
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Model)),
typeof(Model));
Person person = new Person() { Name = "Bill" };
// This returns null
var attribute1 = typeof(Person).GetProperty("Name").GetCustomAttributes(typeof(RequiredAttribute), true).Cast<Attribute>().FirstOrDefault();
// This returns the Required attribute attached to the IPerson.Name interface member
var attribute2 = TypeDescriptor.GetProperties(person)["Name"].Attributes[typeof(RequiredAttribute)];
}
|