Whoever searched for a solution to merge multiple assemblies into a single file probably heard of tools like ILMerge, SmartAssembly, etc.
Another known solution is embedding the DLLs as resources (if anyone's interested, here is a nice article that explains this approach: Load DLL From Embedded Resource[^]).
However on few occasions, I noticed an unnecessary use of these approaches.
If we have these assemblies source codes, then we can achieve the combining by importing all the source code files into a single project at compile time.
In this tip, I'll try to explain briefly how to accomplish that.
For demonstration purposes, let's say we have a console application (our main assembly) that references and uses two class libraries (our secondary assemblies) and we want to combine them all into a single file:
When building this solution, we get three assemblies as expected:
MyExecutable's project file (MyExecutable.csproj) is an XML based file and if we inspect its contents, we can find few
ItemGroup nodes. These nodes contain child elements that define the build processes inputs. These child elements can refer to application's source files that need to be compiled, or resource files that need to be copied or assemblies that need to be included in the build process (if anyone's interested, you can read more about Visual Studio project files on MSDN MSBuild).
Now let's locate the
ItemGroup node that refers to our included assemblies:
Here, we will add a condition that will indicate to MSBuild to use these project references when building
<ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
Release mode, we will include all the source code files from both
MyLibrary2 to be compiled as well. We will do this by using a wild card (
"\**\*.cs") that will include all the CS files in the directory and its subdirectories. The wild card will also include some unwanted source code files (for this case, those are TemporaryGeneratedFile_[guid].cs files in obj folder and AssemblyInfo.cs file in Property folder) so we will have to exclude them:
<ItemGroup Condition=" '$(Configuration)' == 'Release' ">
And that is it, let's save these changes in MyExecutable.csproj file and rebuild the solution in
Last thing I would like to emphasize as a sort of troubleshooting advice, because we are literally moving the compilation of all assemblies source files into a single project, that project needs to be able to compile those files. So you need to consider the following:
- The main assembly needs to have all the references, resources, settings, etc. of the secondary assemblies in order to build successfully.
- All assemblies need to be written in the same .NET language.