jeudi 15 décembre 2016

Pattern for passing values from attributes to method

I'm trying to work out a seamless way of passing method attributes around. Here is a possible implementation:

    [Custom(Greeting = "Hello")]
    public string Test(string name)
    {
        var attributes = MethodInfo.GetCurrentMethod().GetCustomAttributes();
        return SayGreeting(attributes, name);
    }

    private string SayGreeting(IEnumerable<Attribute> attributes, string name)
    {
        var customAttr = attributes.SingleOrDefault(a => a is CustomAttribute) as CustomAttribute;
        return customAttr?.Greeting + " " + name;
    }

However the issues with this are:

  1. It falls apart when using async methods.
  2. It doesn't support getting attributes from interfaces.
  3. It looks ugly, especially when a class has lots of methods. It will also look even more ugly when issues 1 and 2 are dealt with.

I'm thinking that I could fix issue 1 by using callermembername and then getting the method using reflection. I could then fix issue 2 by using more reflection.

The other (probably more elegant) way of fixing it would be to use something like Castle DynamicProxy or .NET's RealProxy. Before I go down this path I'd like to know if anyone has any other suggestions?

Thanks,

Joe





Aucun commentaire:

Enregistrer un commentaire