Access attribute inside interceptor

Feb 7, 2014 at 11:07 AM
Edited Feb 7, 2014 at 11:11 AM

I am using an attribute to mark where interception should take place. Is there any way of accessing this attribute (and therefore its properties) inside the Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) implementation of my call handler?

The following 2 calls just give me the attributes from the proxy and delegate:
IEnumerable<Attribute> attributes = input.MethodBase.GetCustomAttributes();
IEnumerable<Attribute> attributes2 = getNext.GetMethodInfo().GetCustomAttributes();
edit: I realise my attribute could inherit from HandlerAttribute and I could then achieve my goal via a different route, but then the compiler doesn't recognise it as an attribute. Is the solution to this to add a reference to the Unity dlls to all relevant projects?

many thanks,
Feb 9, 2014 at 7:09 AM
If your custom attribute extends HandlerAttribute then users of the custom attribute will have to reference Unity.

If you go with a VirtualMethodInterceptor (instead of the TransparentProxyInterceptor I think you are using) you will be able to retrieve the attributes but that forces all methods to be marked as virtual (if you want to intercept them).

There is another way which I think should work but it gets messy because you will have to look up the method that is being invoked using reflection. First here's the code:
Type[] types = new Type[input.Arguments.Count];

for (int i = 0; i < input.Inputs.Count; i++)
    types[i] = input.Inputs.GetParameterInfo(i).ParameterType;

// This is not nearly complete!
var method = input.Target.GetType()

var attribute = method
    .GetCustomAttributes(typeof(MyTransactionAttribute), false)

Assuming the handler knows the attribute (in this case MyTransactionAttribute) that it wants to find.

One thing missing in this example is that it does not have any error checking. But the bigger potential issue is that the method is being looked up only by name and types. To make this more formally correct you would need to implement overload resolution logic which can get complicated when dealing with inheritance, generics, params, optional parameters, etc.

Randy Levy
Enterprise Library support engineer
Support How-to
Feb 10, 2014 at 9:29 AM
Again, thanks for the reply, much appreciated. I have gone with the handler attribute approach.
Very useful to know the "messy" approach though, just in case.