zoukankan      html  css  js  c++  java
  • 利用 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"));
  • 相关阅读:
    不参加IT培训,如何通过自学的方式成功转行?(蜗牛学院)
    惠普电脑win10关闭自动调节亮度
    原生Ajax发送get、post请求每一步
    HTML5的web 存储localStorage、sessionStorage
    node + multer存储element-ui上传的图片
    html块级元素的水平垂、直居中的方式
    vuex之Mutation(三)
    mint ui的tabBar监听路由变化实现tabBar切换
    Vue使用better-scroll左右菜单联动
    vuex之getter(二)
  • 原文地址:https://www.cnblogs.com/davidchild/p/14840888.html
Copyright © 2011-2022 走看看