利用 RuntimeInformation 来构建运行环境的区别依赖

场景:

构建应用程序时,需要对运行的环境进行判断,或者分别设置。

比如:NETCORE 在跨平台 程序某些特定的目录的指定,在Linux/windows/mac/os/android 环境下运行,指定的目录有所区别. 利用 RuntimeInformation

就很容易构建我们对运行环境的判断。


下面我们给出相对应的场景例子:程序支持 跨平台运行,程序的日志的存放目录,用户临时文件目录进行 预先指定。

1:构建多平台运行的维护的公共类 PlatformArbiter:

public class PlatformArbiter
    {
        public T GetValue<T>(Func<T> windowsValueProvider, Func<T> linuxValueProvider, Func<T> osxValueProvider, Func<T> defaultValueProvider)
        {
            return RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                ? windowsValueProvider()
                : RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
                    ? linuxValueProvider()
                    : RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
                        ? osxValueProvider()
                        : defaultValueProvider();
        }

        public void Invoke(Action windowsValueProvider, Action linuxValueProvider, Action osxValueProvider, Action defaultValueProvider)
        {
            var invoker = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                ? windowsValueProvider
                : RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
                    ? linuxValueProvider
                    : RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
                        ? osxValueProvider
                        : defaultValueProvider;
            invoker();
        }

2:使用 PlatformArbiter

private readonly PlatformIArbiter _platformArbiter;

        public string TmpDirectory => _platformArbiter.GetValue(
            () => Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "AppData\\Local\\Temp"),
            () => "/tmp",
            () => "/tmp",
            () => "/tmp");

        public string DotnetDirectory => _platformArbiter.GetValue(
            () => Path.Combine("C:\\Progra~1", "dotnet"),
            () => Path.Combine("/usr/local/share", "dotnet"),
            () => Path.Combine("/usr/local/share", "dotnet"),
            () => Path.Combine("/usr/local/share", "dotnet"));
原文地址:https://www.cnblogs.com/davidchild/p/14840888.html