Mark Oliver's World

Posted: 31/10/2023

Explicitly Including A DLL In A Project

Have you ever seen this kind of error on running your code:

            System.IO.FileNotFoundException: Could not load file or assembly 'XXXXXXXXXXXXXXX, Version=X.Y.Z.0, Culture=neutral, PublicKeyToken=yyyyyyyy'. The system cannot find the file specified. File name: 'XXXXXXXXXXXXXXX, Version=X.Y.Z.0, Culture=neutral, PublicKeyToken=yyyyyyyy'
            
          

This is easily fixed, by adding the missing package/DLL into your project, and rebuilding.
However what happens when someone does a "remove all unused references" on that project?

Well the DLL reference gets removed, which gives you back the error again, and is only detectable by running your app, so unless you have tests that invoke this behaviour, then you have a sneaky bug.

Note - Most likely you need an Integration test to find this kind of error, as it is a problem with what DLLs are available at runtime for your app, and unit tests may include that DLL in some other way.

To avoid this from happening to you in the future: when you include the pacakage/dll in your project, you need to explicitly reference the DLL in your code.

To make this clear for future developers, I prefer to add a specific class into my code that is responsible for this. It looks something like this:

            
              internal static class MissingDllHack     {         private static <Type within the assembly> youNeedMe;     }
            
          

an example that is forcing System.ValueTuple to be included in your project output folder:

            
              /// <summary>The missing dll hack.</summary>     [UsedImplicitly]     internal static class MissingDllHack     {         /// <summary> Must reference a type in System.ValueTuple so that this dll will be         ///   included in the output folder of referencing projects without requiring a direct         ///   dependency on it. See http://stackoverflow.com/a/22315164/1141360.</summary> #pragma warning disable 169         private static ValueTuple youNeedMe; #pragma warning restore 169     }
            
          

Now the DLL is a compile time problem, so if it is not included, you wont be able to compile your code.


Thanks for reading this post.

If you want to reach out, catch me on Twitter!

I am always open to mentoring people, so get in touch.