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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With