Search code examples
c#.netdependencies.net-assemblyilmerge

Is it possible to internalize/IL-merge a single C# class?


I have an app with a reference to a rather large library DLL (let's call it lib.dll), but it only uses a single class from it (let's call this Helper).

lib.dll has additional transitive references which are all copied to the bin folder of my project upon compilation.

I would seriously like to avoid that overhead and find a way to "copy" or "cross-compile" or "merge" the code that makes up Helper into my main project.

Are there any possibilities for doing so? I would like to avoid IL-merging lib.dll in its entirity.


Solution

  • In some situations you can just embed the third party dlls as embedded resources and resolve the references yourself, as Jeffrey Richter described here.

    In a nutshell, in your entry point:

    AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => {
        string name = new AssemblyName(args.Name).Name;
    
        // Either hardcode the appropriate namespace or retrieve it at runtime in a way that makes sense for your project.
        string resourceName = string.Concat("My.Namespace.Resources.", name, ".dll");
    
        using(var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) {
            var buffer = new byte[stream.Length];
            stream.Read(buffer, 0, buffer.Length);
    
            return Assembly.Load(buffer);
        }
    };