Search code examples
c#.netattributesaopcustom-attributes

Custom attribute on return value with ability to access method input parameters in C#


I'm trying to take an advantage of AOP with custom attributes and I want to implement a custom attribute which affects return method value based on input parameters. There is a way to define an attribute for a return value:

[return: CustomAttribute]
public string Do(string param1)
{
    // do something
}

but I couldn't find a way how add a desired behavior when this attributes is applied. I want to execute some code, based on value of input parameters and in certain cases even change the output value.


Solution

  • C# does not provide any AOP related syntax. [return: CustomAttribute] adds metadata information to return type. That's not what you expect at all. In order to leverage AOP you need to either:

    • Use an external library designed specifically to allow AOP. Here's a nice list of such libraries.
    • If you're using container then it may support AOP. For instance here's a link to StructureMap AOP related documentation.
    • You may try to implement AOP features on your own, but it's pretty hard (especially if you care about performance).