添加一个参数来使用属性的方法 [英] Adding a parameter to a method using attributes

查看:143
本文介绍了添加一个参数来使用属性的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

诚然,这其中是一个长镜头。我工作的审计片,你开你的行动的开始和结束时关闭审核记录。我有好听七拼八凑因此,为了审核的方法,你只需要添加一个 [审计(AuditType.Something)] 属性到它,再加上其他的一些信息如果需要的话,如邮件。然后,使用SNAP,我有一个处理创建审计对象,然后打开和关闭其拦截。

Admittedly, this one's a long shot. I'm working on an auditing piece where you open and close an audit record at the start and end of your action. I have it nicely rigged up so that in order to audit a method, you just have to add an [Audit(AuditType.Something)] attribute onto it, plus some other information if needed, like messages. Then, using SNAP, I have an interceptor that handles creating the Audit object, then opening and closing it.

一个情况下,从同事那里,我们需要有想出了在审计非恒定的消息,这意味着它无法进入属性声明。我已经有大约在类粘审计性,具有喷油器让方法继续之前设置它的想法,但似乎马虎,因为物业是由非审计对象accessable,再加上它会在许多被复制场所。也有方法来创建无属性审计,但它会好得多,能够让事情很好地包裹在属性。

A case came up from a coworker where we would need to have a non-constant message in the audit, meaning it can't go into the attribute declaration. I've had thoughts about sticking an Audit property in the class and having the injector set it before letting the method continue, but that seems sloppy because the property would be accessable by non-audited objects, plus it would be duplicated in a lot of places. There are also ways to create the audit without the attribute, but it would be much nicer to be able to keep things nicely wrapped in the attribute.

理想的情况是,如果我能以某种方式设置它,使之与方法 [审计] 属性访问,我能坚持自己的审计对象从注射器的变量。这是可能的话,或者是它只是一厢情愿?

The ideal case is if I could somehow set it up so that methods with the [Audit] attribute have access to a variable that I could stick their audit object in from the injector. Is this at all possible, or is it just wishful thinking?

推荐答案

如果你有审计属性采取类型的参数键入,其中所提供的键入实施产生的审核消息的接口?例如:

What if you have the Audit attribute take a parameter of type Type, where the provided Type implements an interface that produces your audit message? For instance:

public interface IAuditMessageProvider {
    public String MakeMeAnAuditMessage(/* some args perhaps */);
}

public class PiAuditMessageProvider : IAuditMessageProvider {
    public String MakeMeAnAuditMessage() { return "3.14"; }
}

[Audit(typeof(PiAuditMessageProvider))]
public void myMethod { ... }

然后,你可以使用实例化提供的类型 Activator.CreateInstance ,将其转换为 IAuditMessageProvider ,并调用相关的方法。

Then you could instantiate the provided type using Activator.CreateInstance, cast it to IAuditMessageProvider, and call the relevant method.

这篇关于添加一个参数来使用属性的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆