Reputation:
I found this question - which is very similar to what I'm attempting. However, my use case is a little different.
We have the need to store audit history for business services. However, we need to be able to manually call audit checkpoints during method invocation, not just before and after.
We're using Castle.Core in our project. To accomplish this, I plan to create a custom attribute named AuditContext
for use on our service methods (to audit business logic, etc.) I plan to use Castle DynamicProxy to create a logging proxy that will create a new context object based on the metadata arguments in the attribute object. What I would like to do is inject this object into my method as a method argument, but without having to specify an AuditContext
parameter on each service method we create.
Essentially, instead of this:
[AuditContext(someStaticMetadata)
public BusinessObject BusinessMethod (AuditContext context, ...arguments) {
// ...some logic...
context.checkpoint(someAuditData);
}
I want to be able to do this:
[AuditContext(someStaticMetadata)
public BusinessObject BusinessMethod (...arguments) { // We do not have to specify the context object for every business method...
// ...some logic...
context.checkpoint(someAuditData); // ...but the object is still available, as the parameter has been added by the argument.
}
Or, to make a much more generic example, I want to write this:
[ProvidesParam2]
public Object myFunc (param1) { }
...and end up with a function with this signature:
public Object myFunc (param1, param2) { }
The distilled question is this - Can a C# attribute add a parameter to a method that it decorates, effectively changing the signature of the method at design time?
Thanks!
Upvotes: 2
Views: 1586
Reputation: 28779
Short answer: no. Attributes do actually modify what you could interpret as the signature in special cases (like the calling convention) but they definitely cannot modify the argument list. You can achieve what you want with a custom IL rewriter; something like PostSharp might be able to help (disclaimer: I have no experience at all using PostSharp).
Upvotes: 2