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.
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).
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