Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Attributes To Check Whether to Access a Method

I have a method that is only accessible if a certain criteria is fulfilled, if it's not, then the method won't be executed. Currently, this is how I code the thing:

public void CanAccessDatabase()
{
   if(StaticClass.IsEligible())
   {
      return;
   }
   // do the logic
}

Now, this code is ugly because out of no where there is this if(StaticClass.IsEligible()) condition that is not relevant to the concern of the method.

So I am thinking about putting the IsEligible method in the attribute, so that my code will look like this. If the condition is not fulfilled, then this method will just return without executing the logic below.

[IsEligibleCheck]
public void CanAccessDatabase()
{
   // do the logic
}

Eligibility is a runtime decision, of course.

Any idea on how to code up the logic for IsEligibleCheck ? Thanks

Edit: I know PostSharp can do this, but I am looking at something that works out of box, not depending on any third party library.

like image 397
Graviton Avatar asked Dec 29 '22 07:12

Graviton


1 Answers

Any idea on how to code up the logic for IsEligibleCheck?

This is a perfect spot for AOP.

Edit: I know PostSharp can do this, but I am looking at something that works out of box, not depending on any third-party library.

Is Microsoft considered third-party? If not, you could look at Unity from their Patterns & Practices team. Look at the Interceptor mechanism in Unity.

Otherwise, you effectively have to roll your own implementation using reflection. Effectively what you have to do is wrap your objects in a proxy wherein the proxy uses reflection to check the attributes and interpret them appropriately. If IsEligibleCheck succeeds then the proxy invokes the method on the wrapped object. Really, it's easier to just reuse an already existing implementation.

My advice is just use Unity (or another AOP solution).

like image 68
jason Avatar answered Jan 12 '23 22:01

jason