C# – extern alias, and ILMerge’d assemblies

Yan Cui

I help clients go faster for less using serverless technologies.

Suppose you want to merge an assembly A (AssemblyA.dll) with another assembly B (AssemblyB.dll) with ILMerge into a merged assembly (Merged.dll), and everything works fine until the user of your merged assembly also references that AssemblyB.dll, at which point that user will get Ambiguous reference errors for any reference to types defined in assembly B, for example:

image image

Understandably the compiler is not happy here because it finds duplicated definitions for TypeB under the same namespace in the two versions of the assembly B (the one referenced in the user’s project and the one that’s merged with assembly A).

So how do we get out of this unholy mess?

 

Well, there’s this little known feature in .Net called extern alias which allows you to give referenced assemblies an alias via that little Aliases property in the Properties window for any referenced libraries (one I’m sure we have all seen countless times and wondered what it means).

By default the alias for an assembly is ‘global’, which just means global namespace, but you can change it via the Visual Studio properties window or via command line options to CSC.exe:

imageimage

Now the types defined in the Merged.dll assembly will fall under the Merged namespace and to access them you need to first add a line to your code:

extern alias Merged;

and then anywhere you’re referencing types from the Merged assembly you need to prefix it with Merged:: like the following.

image

You might also want to give AssemblyB an alias just to remove any reasonable doubt which assembly a type comes from whenever you reference a type defined in AssemblyB.

 

Whilst this is a way to get you out of a tight spot, it’s far from a clean solution, and as @BjoernRochel said below, a good general advice is to not merge assemblies that you do not own to begin with:

image


 

Whenever you’re ready, here are 4 ways I can help you:

  1. If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
  2. If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
  3. If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
  4. If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.

 


Leave a Comment

Your email address will not be published. Required fields are marked *