Search code examples
c#.netwinformsperformanceportability

Speeding up loading assemblies at runtime


I'm trying to make my app portable, which means embedding my dependencies into the app itself. I'm using this code:

AppDomain.CurrentDomain.AssemblyResolve += (sender, e) =>
{
    string resource = nameof(x) + "." + new AssemblyName(e.Name).Name + ".dll";
    if (resource.EndsWith(".resources.dll"))
    {
        return null;
    }
    using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource))
    {
        byte[] data = new byte[stream.Length];
        stream.Read(data, 0, data.Length);

        Assembly assembly = Assembly.Load(data);
        return assembly;
    }
};

To load the assemblies at runtime. However, it's quite slow. It takes about 1.2 seconds from start to Form.Shown event, and 400ms is taken up by loading the assemblies at runtime. Is there any way to speed this up? Thanks.


Solution

  • You're essentially using dynamic loading with assemblies. You can try static linking your executable.

    dotnet/ILMerge merges your dependent assemblies into a single assembly.

    There are some caveats though - language resource assemblies don't work correctly, and you can only merge managed DLLs.

    You can always use the command line, but the recommended way is to add a build target to your project file:

      <Target Name="ILMerge">
        <Exec Command="ilmerge.exe /out:app.exe Assem1.dll Assem2.dll" />
      </Target>
    

    and build with:

    msbuild /t:ILMerge