3

Is any way to define attribute like:

public class MyAttribute : Attribute
{
    void OnFunctionInvoke() { ... }
}

And mark some function with that attribute

[MyAttribute]
void SomeFunction() { ... }

When SomeFunction is invoked i want OnFunctionInvoke() to be invoked before.

igorr
  • 141
  • 8
  • Have you looked at the suggestions from [this question](http://stackoverflow.com/questions/14862635/how-to-trace-every-method-called), or [this question](http://stackoverflow.com/questions/559148/how-can-i-add-a-trace-to-every-method-call-in-c)? – Mike Eason May 23 '16 at 09:47

3 Answers3

1

You can try using CodeAccessSecurityAttribute as a by-way:

https://msdn.microsoft.com/en-us/library/system.security.permissions.codeaccesssecurityattribute(v=vs.110).aspx

  using System.Security.Permissions;
  ...

  [AttributeUsage(AttributeTargets.All)]
  public class MyInterceptAttribute: CodeAccessSecurityAttribute {
    public MyInterceptAttribute(SecurityAction action)
      : base(action) {
    }

    public override System.Security.IPermission CreatePermission() {
      //TODO: put relevant code here
      Console.Write("Before method execution!");

      return null;
    }
  }

  ...

  // We demand permissions which in turn leads to CreatePermission() call    
  [MyInterceptAttribute(SecurityAction.Demand)]  
  public void MyMethodUnderTest() {
    Console.Write("Method execution!");
  }

So it's, technically, possible (we exploit security), but it's a by-way only.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

Natively, there's no way to do that. However, AOP frameworks like PostSharp will let you do that kind of thing.

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
0

As Thomas levesque wrote, it is not possible.

Alternative you can considerate using Decorator design pattern.

mjpolak
  • 721
  • 6
  • 24