lundi 3 août 2020

C# Reflection to get attribute attached to interface implementation method

I have a type of TestTopicNotificationHandler and I wish to get the MessageBusSubscription attributes attached to the handle method of any ITopicNotificationHandler<> method that is implemented within the class.

There a couple of scenarios:

  1. There may not be the attribute attached to each interface implementation, as in the case below with Task Handle(OtherNotification notification)
  2. I want to avoid looking up via function name Handle as in this case it would pickup Task Handle(bool notAnInterfaceImplementation) which his not actually a signature of ITopicNotificationHandler
  3. It should also ignore methods signatures which are valid (in terms of ITopicNotificationHandler), but not defined in the class interface list

How can i achieve the above please, to find the linked implementation and pull the attribute from it (without reflecting by method name) similar to below:

var type = typeof(TestTopicNotificationHandler);
var attributes = FindAttributes(type);
// above function call returns the attributes that are defined in the class
// { [MessageBusSubscription("v1\test", QualityOfService.AtMostOnce)], [MessageBusSubscription("v1\yes", QualityOfService.AtMostOnce)]

Where this would be a typical class implementation:

class TestTopicNotificationHandler : ITopicNotificationHandler<TestTopicNotification>, ITopicNotificationHandler<YesNotification>, ITopicNotificationHandler<OtherNotification>
{
    [MessageBusSubscription("v1\test", QualityOfService.AtMostOnce)]
    public Task Handle(TestTopicNotification notification)
    {
    return Task.CompletedTask;
    }
    
    [MessageBusSubscription("v1\yes", QualityOfService.AtMostOnce)]
    public Task Handle(YesNotification notification)
    {
    return Task.CompletedTask;
    }
    
    // this should be ignored as whilst listed, it does not have an attribute attached
    public Task Handle(OtherNotification notification)
    {
        return Task.CompletedTask;
    }

    // this should be ignored as whilst valid interface signature, it is not listed in the implementation list of the class
    public Task Handle(NonListedNotification notification)
    {
        return Task.CompletedTask;
    }   
    
    // this should be ignored it is not an interface
    [MessageBusSubscription("invalid", QualityOfService.AtMostOnce)]
    public Task Handle(bool notAnInterfaceImplementation)
    {
        return Task.CompletedTask;
    }
}




Aucun commentaire:

Enregistrer un commentaire