巧用Environment.UserInteractive 實現(xiàn)開發(fā)和生產(chǎn)環(huán)境的分開調試部署
本文轉載自微信公眾號「UP技術控」,作者conan5566。轉載本文請聯(lián)系UP技術控公眾號。
概述
平常我們在做服務開發(fā)的時候,經(jīng)常是希望本地可以直接調試;在生產(chǎn)環(huán)境是以服務允許的;這時候,一般的做法寫2段代碼,需要什么環(huán)境就注釋那段代碼,這樣很麻煩,這時候就可以利用Environment判斷當前的環(huán)境。C#中獲取系統(tǒng)環(huán)境變量需要用到Environment 類。其中提供了有關當前環(huán)境和平臺的信息以及操作它們的方法。該類不能被繼承,以下代碼得到%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 // 上線更新舊資料,都只會手動執(zhí)行一次
- && 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(null, 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 != null)
- {
- job.Settings = new Quartz.JobDataMap(config.Settings);
- }
- #endregion init job
- job.Call(null, args);
- }
- Console.ReadLine();
- }
- }
- else
- {
- ServiceBase[] ServicesToRun;
- ServicesToRun = new ServiceBase[]
- {
- new MainService()
- };
- ServiceBase.Run(ServicesToRun);
- }
- }
- }