vendredi 27 juillet 2018

C# reflection get implementing property of an interface property

I have an interface that I've defined a custom attribute on a property and I want to retrieve the relevant property from a derived instance of that interface.

public interface ITopicProcessor<T>
{
    [TopicKey]
    string TopicName { get; }

    [OtherAttribute]
    string OtherProperty { get; }

    void Process(T message);
}

public class MyClassProcessor : ITopicProcessor<MyClass>
{
    public string TopicName => "MyTopic";

    public string OtherProperty => "Irrelevant";

    public void Process(MyClass message)
    {
    }
}

I can get close with the following - the main issue is that the derived interface type doesn't seem to have the same custom attributes as the generic type definition. I'm pretty sure it's partly due to needing to use the underlying method implementation rather than use the property value directly

// iType is typeof(ITopicProcessor<MyClass>)
// I also have access to the generic type definition if need be - i.e. typeof(ITopicProcessor<>)
Func<Type, string> subscriberTypeToTopicKeySelector = iType =>
{
    // Creating an instance via a dependency injection framework
    var instance = kernel.Get(iType);
    var classType = instance.GetType();

    var interfaceMap = classType.GetInterfaceMap(iType);
    // interfaceMap.InterfaceMethods contains underlying get_property method, but no custom attributes
    var interfaceMethod = interfaceMap.InterfaceMethods
                                      .Where(x => x.HasAttribute<TopicKeyAttribute>())
                                      .ToList();
    var classMethodInfo = interfaceMap.TargetMethods[Array.IndexOf(interfaceMap.InterfaceMethods, interfaceMethod)];

    return classMethodInfo.Invoke(instance, BindingFlags.Default, null, null, CultureInfo.CurrentCulture)
                          .ToString();
};





Aucun commentaire:

Enregistrer un commentaire