I have the following scenario where registry access is not working with a .Net Standard 2.0 dll. There are two parts to the program shown below...
A Shared library that is .Net Standard 2.0. It references the Microsoft.Win32.Registry nuget package (v4.4). The shared library has the following method in it:
public static void GetRegistryValue()
{
// it does successfully enter this if statment
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var y = Microsoft.Win32.Registry.LocalMachine; // this returns null
var x = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Default); // this throws System.PlatformNotSupportedException: 'Registry is not supported on this platform.'
}
}
A main application that is full .Net Framework. I have tried .4.6.1 and .4.7.1. The main application references the shared library. When the main application calls GetRegistryValue(), it does not work.
Microsoft.Win32.Registry.LocalMachine returns null, so that will not work.
RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Default) throws a System.PlatformNotSupportedException.
What am I doing wrong here?
That's by design. Don't add such Windows only dependencies to a .NET Standard class library. At compile time, it would simply mislead MSBuild/NuGet to choose a wrong assembly (which returns the null
or throws PlatformNotSupportedException
you see).
Such references must be only present in your .NET Framework projects, and about how to move the references and related code base to the upper layer, you have to do you own consideration and refactoring. Too broad for an answer.