public static void Main(string[] args) { try { var isService = !(Debugger.IsAttached || args.Contains("--console") || args.Contains("-c")); var builder = CreateWebHostBuilder(args.Where(arg => arg != "--console" && arg != "-c").ToArray()); if (isService) { var pathToExe = Process.GetCurrentProcess().MainModule.FileName; var pathToContentRoot = Path.GetDirectoryName(pathToExe); builder.UseContentRoot(pathToContentRoot); } WebHostInstance = builder.Build(); var scope = WebHostInstance.Services.CreateScope(); var seedDataService = scope.ServiceProvider.GetService <SeedDataService>(); seedDataService.SeedPeriodsAsync(); //Don't hold up the startup process. Seeding will catch up later. if (isService && RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { WebHostInstance.RunAsService(); } else { WebHostInstance.Run(); } } catch (Exception e) { throw; } }
//public static void Main(string[] args) //{ // CreateWebHostBuilder(args).Build().Run(); //} //public static IWebHostBuilder CreateWebHostBuilder(string[] args) => // WebHost.CreateDefaultBuilder(args) // .UseStartup<Startup>(); public static void Main(string[] args) { string pathToContentRoot; bool isService = !(Debugger.IsAttached || args.Contains("--console")); if (isService) { string pathToExe = Process.GetCurrentProcess().MainModule.FileName; pathToContentRoot = Path.GetDirectoryName(pathToExe); } else { pathToContentRoot = Directory.GetCurrentDirectory(); } string[] webHostArgs = args.Where(arg => arg != "--console").ToArray(); IWebHost host = WebHost.CreateDefaultBuilder(webHostArgs) .UseContentRoot(pathToContentRoot) .UseStartup <Startup>() .Build(); if (isService) { host.RunAsService(); } else { host.Run(); } }
public static void RunAsEnv(this IWebHost host) { bool IsWindowsService = false; Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { using (var process = GetParent(Process.GetCurrentProcess())) { IsWindowsService = process != null && process.ProcessName == "services"; } } if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && IsWindowsService) { System.IO.Directory.SetCurrentDirectory(AppContext.BaseDirectory); host.RunAsService(); } else { if (Environment.CommandLine.Contains("--usebasedirectory")) { System.IO.Directory.SetCurrentDirectory(AppContext.BaseDirectory); } host.Run(); } }
public static async Task Main(string[] args) { var isService = !(Debugger.IsAttached || args.Contains("--console")); var builder = CreateWebHostBuilder(args); if (isService) { string pathToExe = Process.GetCurrentProcess().MainModule.FileName; string pathToContentRoot = Path.GetDirectoryName(pathToExe); builder.UseContentRoot(pathToContentRoot); } else { builder.UseContentRoot(AppContext.BaseDirectory); } IWebHost host = builder.Build(); _log.Debug("test"); if (isService) { host.RunAsService(); } else { host.Run(); } }
public static void Main(string[] args) { var isService = !(Debugger.IsAttached || args.Contains("--console")); if (isService) { var pathToExe = Process.GetCurrentProcess().MainModule.FileName; var pathToContentRoot = Path.GetDirectoryName(pathToExe); Directory.SetCurrentDirectory(pathToContentRoot); } IWebHost host = WebHost.CreateDefaultBuilder(args.Where(arg => arg != "--console").ToArray()) .UseUrls("http://0.0.0.0:9182") .UseStartup <Startup>() .Build(); if (isService) { host.RunAsService(); } else { host.Run(); } System.Globalization.CultureInfo.DefaultThreadCurrentCulture = new System.Globalization.CultureInfo("en-US"); System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = new System.Globalization.CultureInfo("en-US"); }
public void Run() { OneDasConsole console; if (_engine != null && !BasicBootloader.IsUserInteractive) { this.TryStartOneDasEngine(_engine, _webServerOptions.CurrentProjectFilePath); } if (BasicBootloader.IsUserInteractive) { BasicBootloader.SystemLogger.LogInformation("started in user interactive mode (console)"); console = _serviceProvider.GetRequiredService <OneDasConsole>(); if (_webhost != null) { console.RunAsync(_isHosting); _webhost.Run(); } else { console.RunAsync(_isHosting).Wait(); } } else { BasicBootloader.SystemLogger.LogInformation("started in non-interactive mode (service)"); _webhost?.RunAsService(); } }
/// <summary> /// Точка входа в приложение. /// </summary> /// <param name="args">Аргументы запуска приложения.</param> public static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .WriteTo.Console() .WriteTo.File(@"logs\\startup-.log", rollingInterval: RollingInterval.Day) .CreateLogger(); try { Log.Information("Начинается запуск приложения."); if (args.Contains("--service") || args.Contains("-s")) { Log.Information("Найдены флаги '--service' или '-s'. Приложение будет запущено как windows-служба."); string contentRootPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule?.FileName); Log.Information("Начинается построение хоста приложения."); IWebHost host = WebHost.CreateDefaultBuilder(args) .UseContentRoot(contentRootPath) .UseStartup <Startup>() .UseSerilog() .Build(); Log.Information("Построение хоста приложения успешно завершено."); host.RunAsService(); } else { Log.Information("Приложение будет запущено как консольное приложение. Для того, что бы запустить приложение как windows-службу, передайте флаги '--service' или '-s'."); Log.Information("Начинается построение хоста приложения."); IWebHost host = WebHost.CreateDefaultBuilder(args) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <Startup>() .UseSerilog() .Build(); Log.Information("Построение хоста приложения успешно завершено."); host.Run(); } } catch (Exception ex) { Log.Fatal(ex, "Приложение неожиданно завершено."); } finally { Log.Information("Приложение завершается."); Log.CloseAndFlush(); } }
public static void RunAdaptive(this IWebHost host, string[] args) { if (args.IsService()) { host.RunAsService(); } else { host.Run(); } }
/// <summary> /// Запускает сервис как Windows-службу, если не подключен дебаггер /// и в аргументах не передан параметр запуска в режиме консоли /// </summary> /// <param name="webHost">Сконфигурированный WebHost</param> /// <param name="args">Аргументы командной строки</param> public static void RunAsWindowsService(this IWebHost webHost, string[] args) { var isService = !(Debugger.IsAttached || args.Contains("--console")); if (isService) { webHost.RunAsService(); return; } webHost.Run(); }
private static void RunAsService(String[] args) { var assemblyLocationFolder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); if (string.Compare(Environment.CurrentDirectory, assemblyLocationFolder, StringComparison.OrdinalIgnoreCase) != 0) { Environment.CurrentDirectory = assemblyLocationFolder; } IWebHost host = BuildWebHost(args); host.RunAsService(); }
public static void RunWebHost(bool isConsole) { string contentRoot = Directory.GetCurrentDirectory(); if (!isConsole) { string modulePath = Process.GetCurrentProcess().MainModule.FileName; contentRoot = Path.GetDirectoryName(modulePath); } IWebHostBuilder hostBuilder = new WebHostBuilder(); string environment = hostBuilder.GetSetting(WebHostDefaults.EnvironmentKey); IConfigurationRoot hostingConfiguration = new ConfigurationBuilder() .SetBasePath(contentRoot) .AddJsonFile("hosting.json", true) .AddJsonFile("appsettings.json", true) .AddJsonFile($"appsettings.{environment}.json", true) .Build(); hostBuilder .UseKestrel(options => { options.Limits.MaxRequestBodySize = null; }) .UseConfiguration(hostingConfiguration) .UseContentRoot(contentRoot) .ConfigureLogging(log => { log.AddConsole(); log.AddDebug(); }) .UseIISIntegration() .UseStartup <Startup>(); IWebHost host = hostBuilder.Build(); if (isConsole) { host.Run(); } else { host.RunAsService(); } }
public static void Main(string[] args) { var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); try { logger.Info("Icims Proxy Service starting up"); string consoleCommand = "--console"; var isService = !(Debugger.IsAttached || args.Contains(consoleCommand)); var pathToContentRoot = Directory.GetCurrentDirectory(); var webHostArgs = args.Where(arg => arg != consoleCommand).ToArray(); if (isService) { var pathToExe = Process.GetCurrentProcess().MainModule.FileName; pathToContentRoot = Path.GetDirectoryName(pathToExe); } IWebHost Host = BuildWebHost(args).UseContentRoot(pathToContentRoot) .UseStartup <Startup>() .Build(); if (isService) { Host.RunAsService(); } else { Host.Run(); } } catch (Exception ex) { //NLog: catch setup errors logger.Error(ex, "Stopped program because of exception"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } }
public static void Main(string[] args) { // CreateWebHostBuilder(args).Build().Run(); IWebHost host = WebHost.CreateDefaultBuilder(args) .UseKestrel(options => { options.Listen(IPAddress.Any, 7001); }) //7001,如果是其他端口,修改 .UseStartup <Startup>() //使用Startup配置类 .Build(); //Debug状态或者程序参数中带有--console都表示普通运行方式而不是Windows服务运行方式 bool isService = !(Debugger.IsAttached || args.Contains("--console")); if (isService) { host.RunAsService(); } else { host.Run(); } }
public static void Main(string[] args) { bool isService = !(Debugger.IsAttached || args.Contains("--console")); try { IWebHost host = BuildWebHost(args.Where(arg => arg != "--console").ToArray(), isService); Log.Logger.Information($"WebService started: {GetServerAddress( host )}. isService:{isService}"); if (isService) { host.RunAsService(); } else { host.Run(); } } catch (Exception e) { Log.Logger.Error(e, "Program/Main exception"); } }