天天看点

巧用Environment.UserInteractive 实现开发和生产环境的分开调试部署

作者:opendotnet

概述

平常我们在做服务开发的时候,经常是希望本地可以直接调试;在生产环境是以服务允许的;这时候,一般的做法写2段代码,需要什么环境就注释那段代码,这样很麻烦,这时候就可以利用Environment判断当前的环境。C#中获取系统环境变量需要用到Environment 类。其中提供了有关当前环境和平台的信息以及操作它们的方法。该类不能被继承,以下代码得到%systemdrive%的值,即“C:”

string sPath = Environment.GetEnvironmentVariable("systemdrive");
Console.WriteLine(sPath);
           

获取一个值,用以指示当前进程是否在用户交互模式中运行。

public static bool UserInteractive { get; }
           

如果当前进程在用户交互模式中运行,则为true ;否则为 false。

注解

此UserInteractive 属性报告 false 的 Windows 进程或服务(如 IIS)在没有用户界面的情况下运行。如果此属性为 false ,则不会显示模式对话框或消息框,因为没有可供用户与之交互的图形用户界面。

Program范例

internal static class Program
 {
 /// <summary>
 /// 應用程式的主要進入點。
 /// </summary>
 private static void Main(string[] args)
 {
 args = new string[1];
 args[0] = "WeChat.SendTemplateMsgJob";

 bool isReleaseUpdateJob = Environment.UserInteractive // 上線更新舊資料,都只會手動執行一次
 && args.Length >= 1
 && args[0].StartsWith("ReleaseUpdate");
 //Autofac
 AutofacConfig.Bootstrapper();

if (Environment.UserInteractive)
 {
if (args.Length == 0)
 {
 //Console 開啟
 MainService mainService = new MainService();
 mainService.TestStartAndStop(args);
 }
else
 {
 //指定想要測試的 job

#region set Culture en-US

 Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
 Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");

#endregion set Culture en-US

if (isReleaseUpdateJob)
 {
 string jobType = $"BigCRM.WinService.Jobs.{args[0]}";
 ReleaseUpdateJob job = Activator.CreateInstance(Assembly.GetExecutingAssembly().FullName, jobType).Unwrap() as ReleaseUpdateJob;
 job.Call(, args);
 }
else
 {
#region load config

 List<JobConfigItem> jobConfigItems = JobConfigItem.Get();
 JobConfigItem config = jobConfigItems.FirstOrDefault(m => m.JobType == args[0]);

#endregion load config

#region init job

 string jobType = $"BigCRM.WinService.Jobs.{config.JobType}";
 BaseJob job = Activator.CreateInstance(Assembly.GetExecutingAssembly().FullName, jobType).Unwrap() as BaseJob;
 job.CronSchedule = config.CronExpression;
 job.JobType = config.JobType;
 job.BaseSettings = config.Settings;
if (config.Settings != )
 {
 job.Settings = new Quartz.JobDataMap(config.Settings);
 }

#endregion init job

 job.Call(, args);
 }

 Console.ReadLine();
 }
 }
else
 {
 ServiceBase[] ServicesToRun;
 ServicesToRun = new ServiceBase[]
 {
 new MainService()
 };
 ServiceBase.Run(ServicesToRun);
 }
 }
 }
           

继续阅读