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

232 views Asked by At

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.

2

There are 2 answers

3
Trioj On BEST ANSWER

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);
    }
};
5
Titian Cernicova-Dragomir On

If you were using .NET Core the new .NET Linker would be an option. Otherwise, license permitting, and if the class you use does not have too many dependencies and the dll is not obfuscated, you could just copy the code to your application by decompiling the dll with IL Spy