Lambda Function in AllowExecute and CanExecuteMethod

Lambda Function in AllowExecute and CanExecuteMethod

Old forum URL: forums.lhotka.net/forums/t/8218.aspx


shawndewet posted on Thursday, December 24, 2009

Would it be possible to change the AllowExecute and the CanExecuteMethod methods to accept a Lambda Expression instead of a string to indicate the method name that the authorization is to apply to?
It just seems that this would be so much cleaner, providing compile-time validation of method names.

Or perhaps better still, how about changing the CanExecuteMethod method to have an overload that does not require a MethodName parameter, but rather uses reflection to determine the method name in which the call to CanExecuteMethod is being raised? Would the performance impact on this be unacceptable?

lukky replied on Thursday, December 24, 2009

I'm all for lambda expressions wherever a string is expected. I've had it with being bitten by a change in method/property name.

RockfordLhotka replied on Thursday, December 24, 2009

shawndewet:
Or perhaps better still, how about changing the CanExecuteMethod method to have an overload that does not require a MethodName parameter, but rather uses reflection to determine the method name in which the call to CanExecuteMethod is being raised? Would the performance impact on this be unacceptable?

Sadly there's no safe way to actually do this.

CSLA .NET still has some methods (now marked as Obsolete) that actually do this - from much older versions of the framework.

I used to have overloads for things like CanReadProperty() that did exactly this. You can't actually use reflection, but you can use the stack trace.

The problem is that you have to turn off certain compiler optimization features or that isn't reliable. And then it turns out that there are some compiler differences between x86 and x64 platforms that make it unreliable - and that was the point when I gave up and made those overloads obsolete.

Adding a lambda overload for AllowExecute() is a fine idea - that runs once per AppDomain, so the use of reflection there is no big deal.

Adding a lambda in CanExecuteMethod() is maybe OK, but it would require reflecting against the lambda on each method call. I think it is probably fine as long as I leave the string overload intact for cases where people find the performance hit too big.

Of course there's already an overload that takes a PropertyInfo<T>, and there's an item in the wish list to create a MethodInfo instead - to make it more clear and to enable the use of a lambda in the RegisterMethod() call that would come as part of this change. Odds are that I'll use the MethodInfo/RegisterMethod() approach, because it gets rid of the string literal, allows a lambda and doesn't require reflection on a per-call basis.

Copyright (c) Marimer LLC