Question

**I'm using PostSharp Express... not sure that would make a difference in this instance though.

I've got an OnMethodBoundary->OnEntry aspect that successfully multicasts at the assembly level to class members in my own code, but when I attempt to apply it to mscorlib System.IO.StreamReader members, no dice. Based on the searching I've done on the PostSharp web site, here on SO, and on Google, I can't tell what the correct way to go about this is with the current version of PostSharp. Does anyone know? Hopefully I'm just missing something simple :\

Here's the aspect followed by multicast attribute I'm using:

namespace Test.Aspects {
    [AttributeUsage(AttributeTargets.Assembly)]
    [MulticastAttributeUsage(MulticastTargets.Method, AllowMultiple = false)]        
    [Serializable]
    public class PatchStreamReaderAttribute : OnMethodBoundaryAspect {
        public override void OnEntry(MethodExecutionArgs args) {
            System.Threading.Thread.Sleep(1000);
        }
    }
}

[assembly: PatchStreamReader(AttributeTargetMembers = "ReadLine", AttributeTargetAssemblies = "mscorlib", AttributeTargetTypes = "System.IO.StreamReader")]
Was it helpful?

Solution

Usually, when you apply an aspect in a given assembly, PostSharp will modify that assembly during its build process. This, of course, cannot happen for mscorlib or, in fact, for any 3-rd party library you reference but do not build from source code.

This is why PostSharp uses different approach when applying aspects to the referenced assemblies using AttributeTargetAssemblies. Instead of modifying the target 3-rd party assembly, PostSharp will modify the calls from your assembly to the target assembly.

This, of course, gives you less options of where you can inject your code. For example, PostSharp can detect the call to the library's method and inject the aspect around that call. But you cannot inject the aspect around the static or instance constructor of the type from the library.

You also need to pay attention to the AttributeTargetTypes property when applying the aspect. For example, you want to apply the aspect on the calls to the StreamReader.ReadLine() method. This virtual ReadLine() method is originally declared on the TextReader class and StreamReader overrides the method. If you look at the IL, then the method call looks like this:

callvirt instance string [mscorlib]System.IO.TextReader::ReadLine()

This means you need to set AttributeTargetTypes property to "System.IO.TextReader" to apply the aspect to the ReadLine() method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top