IMO the correct way to do this is at the csproj level via multi-targeting - <TargetFrameworks>
etc, and either #if
(in the C#) or conditional file includes (again in the csproj). Ultimately, what you're describing is exactly what multi-targeting is designed to do, and any solution other than "just use multi-targeting" is missing out on a huge feature explicitly aimed at solving these problems. The build mechanism has a "bait and switch" layer whose job it is to ask "what is the target framework of the host application? ok, I'll give them {this version} of the dependency" - which is why the job of transitive dependency resolution is deferred to the top-level application build, rather than library build (libraries don't reliably know the host TFM, for the reasons I'm about to get to).
However, putting that aside:
Your biggest problem here is going to be that: .NET Standard doesn't exist at runtime, only at compile-time; I mean multiple things by this, including the reality that .NET Framework can host .NET Standard, so when you ask:
what is the target framework of the hosting process.
it will never be .NET Standard. If that is just a typo and you mean .NET Core, then you can probably be reasonably safe borrowing these 2 lines from PlatformDetection.cs
:
using System.Runtime.InteropServices;
// ...
public static bool IsFullFramework => RuntimeInformation.FrameworkDescription.StartsWith(
".NET Framework", StringComparison.OrdinalIgnoreCase);
public static bool IsNetCore => RuntimeInformation.FrameworkDescription.StartsWith(
".NET Core", StringComparison.OrdinalIgnoreCase);
is it clean? no. Will it work: yes.