如何在 PostSharp 2.0 中有条件地触发我们的方面

发布于 2024-10-31 15:53:26 字数 454 浏览 0 评论 0原文

我们正在我们的一个项目中引入 PostSharp。到目前为止效果很好!但有一件事我们还没有解决:如何有条件地发出建议。

细节: - 我们有一个属性 StopWatchAttribute,它可以记录运行方法所需的时间 - 此属性接受枚举“LoggingLevel”,该枚举在配置文件中设置,值为 0、1、2 等 - 该参数在运行时在名为 BaseService 的基类中读取: new BaseService().CurrentLoggingSettings - 我们尝试设置像 StopWatchAttribute(new BaseService().CurrentLoggingLevel) 这样的属性构造函数,但出现编译错误:属性参数必须是属性参数类型的常量表达式、typeof 表达式或数组创建表达式。

-->摘要:我们希望有条件地调用建议,并且条件取决于属性构造函数中的参数。

这可以吗?

感谢您的帮助, 安德拉斯

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

残月升风 2024-11-07 15:53:26

无论是否为 PostSharp,您都不能将变量赋予属性。由于您已经从配置中读取值,因此只需将您的方面设置为在 Initialize() 方法上执行相同的操作即可。在方面类中覆盖它,然后将值保存到本地字段。您可以在整个方面使用该字段。这会将值编译成实质上对其进行硬编码的方面。

或者,您可以从建议方法(OnMethodStart 等)中提取配置中的值,以便您可以在运行时在配置中更改它。这是一种更“灵活”的方法,因为它不会硬编码任何内容。

请记住,您的变量是在运行时设置的。 PostSharp 是一个后编译框架,这意味着它在 JIT 知道您的变量之前就已经开始工作了。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文