Can I conditionally control method calls at runtime with attributes?

The Conditional Attribute in .NET allows you to disable the invocation of methods at compile time. I am looking for basically the same exact thing, but at run time. I feel like something like this should exist in AOP frameworks, but I don’t know the name so I am having trouble figuring out if it is supported.

So as an example I’d like to do something like this

So where ever in code there is a call to the M method, it would first call RuntimeConditional and pass in Bob to determine if M should be executed.

Asked on April 7, 2016 in .NET,   C#.
Add Comment
1 Answer(s)

You can actually use PostSharp to do what you want.

Here’s a simple example you can use:

[Serializable]
public class RuntimeConditional : OnMethodInvocationAspect
{
    private string[] _conditions;

    public RuntimeConditional(params string[] conditions)
    {
        _conditions = conditions;
    }

    public override void OnInvocation(MethodInvocationEventArgs eventArgs)
    {
        if (_conditions[0] == "Bob") // do whatever check you want here
        {
            eventArgs.Proceed();
        }
    }
}

Or, since you’re just looking at “before” the method executes, you can use the OnMethodBoundaryAspect:

[Serializable]
public class RuntimeConditional : OnMethodBoundaryAspect 
{
    private string[] _conditions;

    public RuntimeConditional(params string[] conditions)
    {
        _conditions = conditions;
    }

    public override void OnEntry(MethodExecutionEventArgs eventArgs)
    {
        if (_conditions[0] != "Bob")
        {
            eventArgs.FlowBehavior = FlowBehavior.Return; // return immediately without executing
        }
    }
}

If your methods have return values, you can deal with them too. eventArgs has a returnValue property that is settable.

Answered on April 7, 2016.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.