Adding a parameter to a method using attributes

给你一囗甜甜゛ 提交于 2019-12-11 03:43:33

问题


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.

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?


回答1:


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 { ... }

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



来源:https://stackoverflow.com/questions/10217698/adding-a-parameter-to-a-method-using-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!