简体   繁体   中英

Postsharp 3rd party class

I need decorate all method from class in 3rd party DLL. I use C# 5.0 and postsharp 3.1. Of course I can do something like this.

//In 3rd party library
class A
{
    public virtual int foo(string a) {}

    public virtual void foo2() {}
}

//In my
class B : A
{
    public override int foo(string a) {
        int result = base.foo(a);
        //Do something
        return result;
    }

    public override void foo2() {
        base.foo2();
        //Do something
    }
}

do something is always the same.
I do not want to copy all of method that is ugly. Some idea what can I use or google? Thank you

Let's say you created OnMethodBoundary aspect to add some custom code at the end of the method:

[Serializable]
public class MyTestAttribute : OnMethodBoundaryAspect
{
    public override void OnSuccess(MethodExecutionArgs args)
    {
        // Do something.
    }
}

To apply this aspect to a 3-rd party assembly, you can apply it in your project and set AttributeTargetAssemblies property to the name of the 3-rd party assembly. This will cause PostSharp to modify your assembly and decorate the calls to the 3-rd party assembly with your custom code.

[assembly: MyTest(AttributeTargetAssemblies = "SomeLibrary")]

I guess that this would be a good case for Castle Dynamic Proxy .

If third-party classes aren't sealed (thus, they allow inheritance and target methods or properties are polymorphic), you should be able to create a run-time proxy (ie a run-time derived class).

Finally, you'll create a factory method that would return proxied instances of the whole third-party classes.

PostSharp works on CIL level and thus it is possible to take the command-line tool (postsharp.4.0-x86.exe) and weave aspects into almost any assembly.

It goes like this:

postsharp.4.0-x86 /X:MyDependency.PostSharp.config MyDependency.dll

The config file is regular PostSharp configuration file (like .pssln and .psproj):

http://doc.postsharp.net/configuration-schema

However, one needs to be careful about license to the third party library.

EDIT: As a sidenote - this scenario is NOT officially supported by PostSharp - so you are on your own if you run into any problems.

You can use a technique that PostSharp documentation calls Method Interception . It works by modifying your code - inserting extra code at sites where you call the 3rd party code, instead of touching the 3rd party code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM