Interceptor for static method

810 Views Asked by At

We have legacy code and want to know when application call 'Execute' method.

Legacy code structure:

public class CmsJob
{
    public static string Execute()
    {
    }
}

Is it possible to use IInterceptor or PostSharp.dll to implement additional operation after or before execution static method?

1

There are 1 best solutions below

0
AlexD On

It is possible to intercept the static method with PostSharp, even if it's declared in an external assembly that you can't modify. You can implement your own OnMethodBoundaryAspect.

[PSerializable]
public class MyAspect : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionArgs args)
    {
        // Code to execute before the target method ...
    }
}

Then apply this aspect in your project on the assembly level and set these properties: AttributeTargetAssemblies, AttributeTargetTypes, AttributeTargetMembers.

[assembly:MyAspect(AttributeTargetAssemblies="ThirdPartyAssembly",
                   AttributeTargetTypes="SomeNamespace.CmsJob",
                   AttributeTargetMembers="Execute")]