I'm trying to write a custom attribute that I can apply to methods that will prevent the method from being called when Transaction.Current
is null. I currently have a basic attribute class that throws an exception if that item is null. Here it is:
[AttributeUsage(AttributeTargets.Method)]
public class RequiresTransactionAttribute : System.Attribute
{
public RequiresTransactionAttribute()
{
if (Transaction.Current == null)
{
throw new Exception("requires transaction");
}
}
}
The problem is that this does not cause method calls to fail in my tests.
I've read that these attributes are converted to meta data and so this constructor is never executed because it's optimized out unless I specifically use reflection to cause the attribute to be executed.
Is it possible to prevent a method from being called based on such a requirement as mine using attribute approach, or perhaps some other better method?
Copyright Notice:Content Author:「Ryan」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/48312029/can-an-attribute-be-used-to-prevent-a-method-from-being-called