This is not possible with the present version of PostSharp.
PostSharp works by transforming assemblies prior to being loaded by the CLR. Right now, in order to do that, two things have to happen:
- The assembly must be about to be loaded into the CLR; you only get one shot, and you have to take it at this point.
- After the transformation stage has finished, you can't make any additional modifications. That means you can't modify the assembly at runtime.
The newest version, 1.5 CTP 3, removes the first of these two limitations, but it is the second that's really the problem. This is, however, a heavily requested feature, so keep your eyes peeled:
Users often ask if it is possible to use PostSharp at runtime, so aspects don't have to be known at compile time. Changing aspects after deployment is indeed a great advantage, since it allow support staff to enable/disable tracing or performance monitoring for individual parts of the software. One of the cool things it would enable is to apply aspects on third-party assemblies.
If you ask whether it is possible, the short answer is yes! Unfortunately, the long answer is more complex.
Runtime/third-party aspect gotchas
The author also proceeds to outline some of the problems that happen if you allow modification at runtime:
So now, what are the gotchas?
- Plugging the bootstrapper. If your code is hosted (for instance in
ASP.NET or in a COM server), you
cannot plug the bootstrapper. So any
runtime weaving technology is bound to
the limitation that you should host
the application yourself.
- Be Before the CLR. If the CLR finds the untransformed assembly by its own,
it will not ask for the transformed
one. So you may need to create a new
application domain for the transformed
application, and put transformed
assemblies in its binary path. It's
maybe not a big problem.
- Strong names. Ough. If you modify an assembly at runtime, you will have to
remove its strong name. Will it work?
Yes, mostly. Of course, you have to
remove the strong names from all
references to this assembly. That's
not a problem; PostSharp supports it
out-of-the-box. But there is something
PostSharp cannot help with: if there
are some strongly named references in
strings or files (for instance in
app.config), we can hardly find them
and transform them. So here we have a
real limitation: there cannot be
"loose references" to strongly named
assemblies: we are only able to
transform real references.
- LoadFrom. If any assembly uses Assembly.LoadFrom, Assembly.LoadFile
or Assembly.LoadBytes, our
bootstrapper is skipped.