Merge multiple dll ‘s into one WPF application

Tags: .NET, WPF

It’s pretty standard scenario to have your application reference assemblies that are not part of the .net framework.  In those instances the default behaviour is for VS to sit those dll’s along side your built .exe file.

Of course the application won’t run without them, but it can be a pain (or at least unwanted) to have to deploy these dll’s with the application.  Especially if you want to share/move the .exe file around the place.

ILMerge to the rescue, this is a groovy little tool from Microsoft that will “Merge” your dll’s into a single dll/exe.  However, this does not work with WPF applications and was never designed too.

After a little digging around I found this solution, it does require a little code, but nothing heavy.  I’d actually rather have this piece of code than flakey post build commands anyway.

Essentially you add your dll to the application in VS, set it as an Embedded Resource and put the code chunk below into the Application OnStartup event.

protected override void OnStartup(StartupEventArgs e)
{
	base.OnStartup(e);
	AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => {

		string resourceName = "<Your namespace>.<folder name dll is in>." + new AssemblyName(args.Name).Name + ".dll";

		try {
			using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) {
        	        	Byte[] assemblyData = new Byte[stream.Length];
		                stream.Read(assemblyData, 0, assemblyData.Length);
        	        	return Assembly.Load(assemblyData);	
			}
	        } catch (Exception ex) {
			throw new System.IO.FileLoadException("Cannot find dll embedded resource - " + resourceName, ex);
	        }
	};
}

Don't forget to change the reference to the assembly to "Copy Local = False", we don’t need that to copy anymore!

Further:
Costura is a tool/add in that will basically do the above, without writing the code.  I’m happy with the code!




comments powered by Disqus