Как перехватить вызов не виртуального метода из / в сторонние библиотеки в .Net?

Я думаю, что мне нужно что-то, что люди .net называют «прозрачным динамическим прокси», но все реализации, которые я видел до сих пор (Castle DynamicProxy, Spring.NET AOP и т. Д.), Требуют, чтобы я выполнил хотя бы одно из них:

Declare intercepted method as virtual Wrap class and create instances of the wrapper instead of wrapped class Change inheritance or implement interfaces

Очевидно, что если и вызывающий, и вызываемый являются не виртуальными и из сторонних библиотек с закрытыми исходными кодами, что имеет место, я ничего не могу поделать.

Если бы C # был динамическим языком, таким как Python, я бы сделал что-то вроде этого:

foo = ThirdyPartyLibA.Foo()
def interceptor(self, *args, **kwargs):
    do_something_before(self, *args, **kwargs)
    result = ThirdyPartyLibB.Bar.intercepted(self, *args, **kwargs)
    do_something_after(self, result, *args, **kwargs)
    return result
foo.bar.intercepted = interceptor # bar is an instance of ThirdyPartyLibB.Bar
foo.do_its_job() # Foo.do_its_job calls Bar.intercepted

Мне нужно это, чтобы изменить плохое поведение ThirdyPartyLibA.Foo при взаимодействии с ThirdyPartyLibB.Bar. Я точно знаю, что вызывает такое поведение, и как именно изменить Foo или Bar, чтобы исправить эту ошибку, благодаря дизассемблерам.

Некоторые (очень маловероятные идеи):

Disassemble ThirdyPartyLibA, make changes in code and generate a compatible assembly (unlikely to work because it's a strong-named assembly) Edit binary to make Foo's buggy methods virtual and change whatever is necessary for it to remain a valid assembly so I can use dynamic proxies (very unlikely to work, also because of the same reason as the idea above) Find a transparent dynamic proxy implementation that fits (I think there is none based on this forum thread: http://www.pcreview.co.uk/forums/overriding-non-virtual-methods-using-il-and-reflection-emit-t2605695.html) Contact the company that created the library (they don't support the product anymore) Stop using the library or use an alternative (impossible, since it's part of the runtime of a RAD IDE that we are tied to because there is a HUGE amount of code written using the IDE own language) Control the calls to the problematic methods to avoid the bug (we already did this but it didn't solve the problem completely)

У тебя есть другая идея?

PS: извините за мой плохой английский. Кроме того, извините за мой Python. Этот код здесь только для иллюстрации того, что мне нужно, не воспринимайте его как рецепт, потому что это ужасно.

Ответы на вопрос(2)

Ваш ответ на вопрос