PostSharp on assemblies I don't have source for
Asked Answered
A

1

7

In the examples on their website, PostSharp has a demo of intercepting calls in main system assemblies. I have tried a few times to setup and replicate said intercept calls on assemblies I don't have the source code for with no success.

My approach was to simply place the assembly level attribute targeting the namespace and method I wanted to instrument. This has never worked for me.

something like:

[assembly: Trace("MyCategory", AttributeTargetTypes = "My.BusinessLayer.*")]

Am I missing something here? Can I not do a runtime injection of my instrumentation aspect on a assembly if I don't have the source pulled in for it? I thought I could do runtime injections...

Thanks.

Anjanetteanjela answered 7/7, 2010 at 16:32 Comment(0)
S
5

You can trace methods of other assemblies by specifying:

[assembly: Trace("MyCategory",
                 AttributeTargetAssemblies="xyz",
                 AttributeTargetTypes = "My.BusinessLayer.*")]

However, the external assembly will not be modified! Only calls from the current project to the external assembly can be modified.

It is currently not easy to modify assemblies you don't have the source of. This is possible, but is considered an advanced scenario and requires custom coding.

Springfield answered 7/7, 2010 at 17:40 Comment(5)
Gael, So... If I created a unit test and I wanted to intercept a method call because it's a "high cost" method... I could add the interception as you are talking about above, but only the unit test's calls would intercept if I called directly, but not the assembly I was testing calls to the same method? If I wanted to do that, I'd have to have the intercept in the assembly I am testing? -- Do you have any examples of said advanced scenario available? I'd be very interested to see that.Anjanetteanjela
Yes, that's it. Say you have assemblies A and B, B references A. Both A and B call method Thread.Sleep. Inside project B, you put an aspect on Thread.Sleep. Only calls from B to Thread.Sleep will be intercepted, not calls from A.Springfield
And since you seem to like P-Invoke, it's also possible to put aspects on P-Invoke methods :).Springfield
excellent! You did mention that advanced scenarios require custom coding to intercept globally (a & b calls are all intercepted to Thread.Sleep) ... any chance of some sample code for that?Anjanetteanjela
There is no example. Basically, you should invoke the PostSharp command line with a custom project (psproj) including a task that implements IAnnotationProvider; this provider provides the aspects. The only difficulty is to write this IAnnotationProvider. The default provider just reads custom attributes.Springfield

© 2022 - 2024 — McMap. All rights reserved.