views:

132

answers:

2

I have looked at a few of the well-known AOP-oriented frameworks for .Net such as PostSharp, bltoolkit, Castle, Cecil, and Policy Injection Block from Microsoft. Perhaps I am ignorant, but it appears that these frameworks do not provide the ability to inject code while the class is being loaded by the virtual machine, before it is visible to the application. They all appear to rely on either application use of a factory or class/method level attributes that provide the meta-data needed for compile-time manipulation of assemblies. The critical feature of java.lang.instrument I'm looking for is to simply inject interceptors around method calls without changing source (attributes on methods/classes) or rebuilding existing assemblies to inject the interception code. Am I naive in thinking the CLR security model can support this?

+1  A: 

Have you seen this write-up:comparing IoC frameworks?

Robert
+2  A: 

You are correct that most of the AOP frameworks for .NET requires you to create objects using a special kind of factory or the like. The reason for this is that (custom) attributes in .NET are passive, so you need some kind of framework that can inspect those attributes in a timely fashion.

There are a few AOP frameworks for .NET that use either code generation or IL weaving (modification of the Intermediate Language byte code after normal compilation) to allow interception, but I always stay away from things like that - there's a lot of inherent problems in such an approach.

I once had an opportunity to ask Anders Hejlsberg whether we couldn't get 'active' attributes in .NET, but his response was that if Microsoft provided such a capability, they might as well stop all further development of the platform, because it would be impossible to move .NET forward without breaking compatibility with someone's code (I may be misrepresenting his answer, but the essential part is that it has been considered and rejected - apparently for good reasons).

That said, .NET has an Instrumentation API that can intercept any method call. That API, however, is an unmanaged API (it requires you to write unmanaged C++ code) and (IIRC) requires you to host the .NET app yourself. It is a very heavy-handed approach. You should also be aware that Instrumentation can potentially harm the performance of your application.

Mark Seemann
I was hoping to avoid the unmanaged API. Thanks for the interesting information!
Todd Stout