PostSharp and ILMerge [Solved?]

by Gael Fraiteur on 25 Jul 2008

In my previous post I claimed that it was not possible, in general, to merge assemblies enhanced by PostSharp, because it would break the assembly references stored as strings in aspect serialization data.

I did not realize that the BinaryFormatter provides a way to solve our problem. It is indeed possible to provide its own SerializationBinder, whose role is precisely to return the System.Type corresponding to an assembly name and a type name. We can provide a custom binder to redirect merged assemblies.

This is the feature I have added to build 1.0.10.411 available for download in the builds section; I could still do it in 1.0 since it is a no-risk feature, breaking nothing existing (if you don't use it, nothing can go wrong).

I have added a new class PostSharp.Laos.LaosSerializationBinder. You can set the static property Current to your own implementation of SerializationBinder. If you don't set it, nothing is changed. The LaosSerializationBinder class it itself derived from SerializationBinder and implements the feature we need: assembly retargeting. So all you have to do is to create an instance of this class, set up retargeting policies, and assign it to LaosSerializationBinder.Current.

The following code sets up PostSharp Laos so that references to 'MergedPostSharpLib.dll' are retargeted to 'MergedPostSharp.exe' (supposing that the library has been merged into the executable):

LaosSerializationBinder binder = new LaosSerializationBinder();
binder.Retarget("MergedPostSharpLib", "MergedPostSharp");
LaosSerializationBinder.Current = binder;

The only thing you have to really take care about is to set up the binder before the first aspect is deserialized. Aspect deserialization is triggered from static constructors of enhanced classes, so you may need to initialize the weaver very soon, and eventually to refactor your "Main(string args[])" method.

Apart from that, it should work very well.

Happy PostSharping!

~Gael