C# – extern alias, and ILMerge’d assemblies

Yan Cui

I help clients go faster for less using serverless technologies.

This article is brought to you by

Don’t reinvent the patterns. Catalyst gives you consistent APIs for messaging, data, and workflow with key microservice patterns like circuit-breakers and retries for free.

Try the Catalyst beta

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 3 ways I can help you:

  1. Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
  2. I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
  3. Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.

Leave a Comment

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