2
votes

We are in the progress of introducing PostSharp in one of our projects. It's been working great so far! There is one thing though that we haven't managed to solve: how to fire an advice conditionally.

Details: - we have an attribute StopWatchAttribute which makes it possible to record the time needed to run methods - this attribute accepts an enumeration "LoggingLevel" which is set in the config file with values like 0, 1, 2 etc - this parameter is read in a base class called BaseService during runtime: new BaseService().CurrentLoggingSettings - we tried to set up the attribute constructor like StopWatchAttribute(new BaseService().CurrentLoggingLevel) but we get a compile error: an attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.

--> summary: we would like the advice to be called conditionally and the condition depends on the parameter in the constructor of the attribute.

Is this possible to do?

Thanks for your help, Andras

1

1 Answers

4
votes

You cannot give variables to attributes, PostSharp or not. Since you're already reading the values from the config, just set your aspect to do the same on the Initialize() method. Override it in the aspect class and then save the value to a local field. You can use that field throughout the aspect. This compiles the value into the aspect essentially hard coding it.

Or, you can pull the value from the config from your advice method (OnMethodStart, etc) so that you can change it in the config at runtime. This is a more 'flexible' way to do it as it doesn't hard code anything.

Remember, your variables are being set at Runtime. PostSharp is a post-compile framework which means it does it's work long before your variables are even known to JIT.