问题
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