title: Issue with nested DLL referencing in a self-contained .Net Core web app running as a Windows service
body: <p><strong>The Error</strong></p>
  <p>First off, lets start with the error message:</p>
  <blockquote>
  <p>System.BadImageFormatException: 'Could not load file or assembly 'System.Management, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. Reference assemblies should not be loaded for execution.  They can only be loaded in the Reflection-only loader context. (0x80131058)'</p>
  </blockquote>
  <p>In my experience, this type of error usually occurs if the DLL is missing, or it's not in the expected format/version. However, I cannot work out what I need to do to resolve this error.</p>
  <p><strong>The Setup</strong></p>
  <p>The main project is an ASP.Net Core 3.1 application.</p>
  <p>It is configured to be able to run as a Window service and support Web API and MVC frameworks. So my Program.cs looks something like this:</p>
  <pre><code>public class Program
  {
      public static void Main(string[] args)
      {
          CreateHostBuilder(args).Build().Run();
      }
  
      public static IHostBuilder CreateHostBuilder(string[] args)
      {
          var builder = Host.CreateDefaultBuilder(args)
              .ConfigureWebHostDefaults(webBuilder =&gt;
              {
                  webBuilder.UseStartup&lt;Startup&gt;();
              });
  
          builder.UseWindowsService();
  
          return builder;
      }
  }
  </code></pre>
  <p>That part all works great, I can run the app as a Windows service and serve razor views and web API endpoints, etc.</p>
  <p>However, there are more projects in this solution. I have a couple of .Net 4.6 class libraries projects that are referenced by the service app. So my solution looks something like this:</p>
  <ul>
  <li>Service App (NET CORE 3.1)</li>
  <li>Lib 1 (NET 4.6)</li>
  <li>Lib 2 (NET 4.6)</li>
  </ul>
  <p>Service App references Lib 1, and Lib 1 references Lib 2.</p>
  <p>Any code is either of these two libraries works fine and can be used by the service app.</p>
  <p>The problem is that Lib 2 references <a href="https://www.nuget.org/packages/System.Management/" rel="nofollow noreferrer">System.Management DLL</a>, and this is what is causing the error. Whenever I use a function that uses that DLL, I get the error above.</p>
  <p><strong>The Attempts So Far</strong></p>
  <p>My attempts so far have including:</p>
  <ul>
  <li>Setting the DLL to &quot;copy to output&quot;</li>
  <li>Adding the DLL reference directly to the web service app</li>
  <li>Manually copying the DLL to the output folder. Both debug, and publish folder (note: publish is set to &quot;self contained&quot; application)</li>
  </ul>
  <p><strong>The Question</strong></p>
  <p>Basically, how can I resolve this issue? Or at least, how can I further debug the problem to potentially find a solution.</p>