Delay-loading assemblies in .NET

I was trying to find a .NET equivalent to the “/delayload” option that the linker has for unmanaged code. For the uninitiated, “/delayload:someDLL.dll” changes the resulting .EXE/.DLL so that someDLL.dll will not be loaded until the first time a function in it is called. It’s a handy option you can use so that you do not need to install someDLL.dll on computers where you know it’s not going to be needed.

I wanted to find a way to the same thing with .NET assemblies. I have an Assembly1.DLL which will sometimes call into an Assembly2.DLL. But not always. And on computers where Assembly2.DLL will never be called, I don’t want to install it on the system at all.

I couldn’t find any equivalent to “/delayload:Assembly2.DLL”. I figured that it would be possible to achieve the desired effect using a proxy class with System.Assembly.Load and System.Type.InvokeMember. I couldn’t find any existing code on the Internet that did this, so I set about writing one. I called it DelayLoadProxy. It was using “method intercept” techniques and Reflection and attributes, and was going to be all cool and nifty. Development was going along really well, for about a day and half.

Then I thought, maybe I should go talk to our resident .NET expert, see if he knows of any existing code that does this. But the answer was worse than I could have imagined. In fact, “/delayload” is the default behaviour of .NET!

That’s right… you don’t need “/delayload” at all. By default, an assembly is not loaded at all until it’s time to run code from it. If you never run code in it, then the assembly need not even be present on the target system; nobody will ever look for it.

So all that work was for nothing.

I guess my approach still has the trivial advantage that you don’t even need the second assembly to be present even when compiling the first assembly. Whatever…

2 Responses to “Delay-loading assemblies in .NET”


  • In mixed-mode programming, I found that the assembly delay load doesn’t occur on the actual call like the /delayload option does, it occurs on entry to a compilation unit (a .cpp file) that includes a reference to assembly to be delay loaded. So, if you want to have a situation where you do not need the assembly to exist, you must not call any methods in a file that contains references to that assembly.

  • This doesn’t help when your DLL uses COM interop, and regasm fails if ALL referenced DLLs can’t be loaded (or at least found).

    RegAsm : error RA0000 : Could not load file or assembly ‘3rdparty.app.library, Version=5.3.0.0, Culture=neutral, PublicKeyToken=0123456789abcdef’ or one of its dependencies. The system cannot find the file specified.

    🙁

Leave a Reply

Categories

Archives