samedi 24 octobre 2015

Runtime code generation, custom attributes on properties and CustomAttributes versus GetCustomAttributes

I'm building up a library for handling some network devices. The interface needs to return data of type that depends on what particular device is queried. Additionally, as the client system works with such dynamic data by custom attributes attached to entity properties, I need to be able to add attributes dynamically to my dynamic entities' properties.

Here is how I create the entity type and decorate a property with an attribute (I omitted the code for defining either getters and setters or the backing field)

// creates type builder for requested entity schema
var typeBuilder = GetTypeBuilder();
var attrType = typeof(TestAttribute);

var propertyBuilder = typeBuilder.DefineProperty("TestProp", PropertyAttributes.HasDefault, propertyType, null);
var ctorInfo = attrType.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault();
var attributeBuilder = new CustomAttributeBuilder(ctorInfo, new object[] { },
    // here I pass collections of data in order to initialize the attribute
    attrProperties.ToArray(), attrPropertiesValues.ToArray(),
    attrFields.ToArray(), attrFieldsValues.ToArray());

propertyBuilder.SetCustomAttribute(attributeBuilder);

var type = typeBuilder.CreateType();

and here is how I later check for the attribute existence on the property

var obj = Activator.CreateInstance(type);

var prop = obj.GetType().GetProperties().First(x => x.Name == "TestProp");
var attributes = prop.GetCustomAttributes(typeof(TestAttribute), false);

The problem is that the last line of code (calling GetCustomAttributes) gives me an empty array while the property prop.CustomAttributes contains an array of one element and that element is my TestAttribute.

Can anyone explain to me the difference? I think I need to have this GetCustomAttributes to work as I cannot be sure what way of retrieving the attributes is used in the client system.

Does it matter that TestAttribute is a member class of my tests' suite class?





Aucun commentaire:

Enregistrer un commentaire