static async Task Main(string[] args) { if (WindowsServiceHelpers.IsWindowsService()) { Directory.SetCurrentDirectory( Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) ); } var host = new WebHostBuilder() .ConfigureAppConfiguration(Startup.CreateConfiguration(args)) .UseKestrel((context, options) => options.Configure(context.Configuration.GetSection("Kestrel"))) .UseStartup <Startup>() .Build(); if (WindowsServiceHelpers.IsWindowsService()) { host.RunAsService(); } else { await host.RunAsync(); } //var avalonia = AppBuilder // .Configure(new Application()) // .UsePlatformDetect() // .UseReactiveUI() // .SetupWithoutStarting() // .Start<MainWindow>(); }
public static void Main(string[] args) { #if DEBUG LogManager.ThrowExceptions = true; #endif string logDir = string.Empty; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { logDir = "/var/log/CNCLib.Serial.Server"; } else { var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); if (!Directory.Exists(localAppData) || WindowsServiceHelpers.IsWindowsService()) { // service user localAppData = Environment.GetEnvironmentVariable("ProgramData"); } logDir = $"{localAppData}/CNCLib.Serial.Server/logs"; } GlobalDiagnosticsContext.Set("logDir", logDir); var logger = NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger(); try { logger.Info("Starting (Main)"); ProgramUtilities.StartWebService(args, CreateHostBuilder); } catch (Exception e) { logger.Error(e); throw; } }
/// <summary> /// Sets the host lifetime to WindowsServiceLifetime, sets the Content Root, /// and enables logging to the event log with the application name as the default source name. /// </summary> /// <remarks> /// This is context aware and will only activate if it detects the process is running /// as a Windows Service. /// </remarks> /// <param name="hostBuilder">The <see cref="IHostBuilder"/> to operate on.</param> /// <param name="configure"></param> /// <returns>The same instance of the <see cref="IHostBuilder"/> for chaining.</returns> public static IHostBuilder UseWindowsService(this IHostBuilder hostBuilder, Action <WindowsServiceLifetimeOptions> configure) { if (WindowsServiceHelpers.IsWindowsService()) { // Host.CreateDefaultBuilder uses CurrentDirectory for VS scenarios, but CurrentDirectory for services is c:\Windows\System32. hostBuilder.UseContentRoot(AppContext.BaseDirectory); hostBuilder.ConfigureLogging((hostingContext, logging) => { logging.AddEventLog(); }) .ConfigureServices((hostContext, services) => { services.AddSingleton <IHostLifetime, WindowsServiceLifetime>(); services.Configure <EventLogSettings>(settings => { if (string.IsNullOrEmpty(settings.SourceName)) { settings.SourceName = hostContext.HostingEnvironment.ApplicationName; } }); services.Configure(configure); }); } return(hostBuilder); }
public void ConfigureServices(IServiceCollection services) { services.AddLogging(builder => { builder .AddConfiguration(Configuration.GetSection("Logging")) .AddDebug() .AddConsole(); if (WindowsServiceHelpers.IsWindowsService()) { builder.AddEventLog(); } }); services.AddMvcCore() .AddApiExplorer() .AddAuthorization() .AddCors() .AddDataAnnotations() .AddFormatterMappings(); services.AddAkavacheState(() => new State()); services.AddHostedService <DiscoveryService>(); services.AddSignalR(); }
public static ApplicationModes GetApplicationMode(IStartupContext startupContext) { if (startupContext.Help) { return(ApplicationModes.Help); } if (OsInfo.IsWindows && startupContext.RegisterUrl) { return(ApplicationModes.RegisterUrl); } if (OsInfo.IsWindows && startupContext.InstallService) { return(ApplicationModes.InstallService); } if (OsInfo.IsWindows && startupContext.UninstallService) { return(ApplicationModes.UninstallService); } if (OsInfo.IsWindows && WindowsServiceHelpers.IsWindowsService()) { return(ApplicationModes.Service); } return(ApplicationModes.Interactive); }
public static int Main(string[] args) { var cmd = BuildCommand(); cmd.UseMiddleware(invocation => { ParseResult result = invocation.ParseResult; var dir = result.ValueForOption(Options.WorkingDirectory); if (dir != null) { Directory.SetCurrentDirectory(dir); } }); cmd.UseDefaults(); cmd.UseHost(BuildHost, builder => { if (WindowsServiceHelpers.IsWindowsService()) { builder.ConfigureServices(services => { services.RemoveService <IHostLifetime, InvocationLifetime>(); }); } }); return(cmd.Build().Invoke(args)); }
public static async Task Main(string[] args) { var logPath = "."; if (WindowsServiceHelpers.IsWindowsService()) { logPath = AppContext.BaseDirectory; } logPath = Path.Combine(logPath, "smallrss.service.log"); const string logOutputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}"; Log.Logger = new LoggerConfiguration() .MinimumLevel.Is(WindowsServiceHelpers.IsWindowsService() ? LogEventLevel.Debug : LogEventLevel.Verbose) .MinimumLevel.Override("Microsoft", LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Console(outputTemplate: logOutputTemplate) .WriteTo.File(logPath, LogEventLevel.Verbose, outputTemplate: logOutputTemplate, fileSizeLimitBytes: 10_000_000, rollOnFileSizeLimit: true, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(1)) .CreateLogger(); var host = Host .CreateDefaultBuilder(args) .UseWindowsService() .ConfigureWebHostDefaults(webBuilder => webBuilder .UseKestrel() .UseStartup <Startup>() .UseSerilog() ) .Build(); await host.RunAsync(); }
public override Task StartAsync(CancellationToken cancellationToken) { if (WindowsServiceHelpers.IsWindowsService()) { _logger.LogInformation("Starting Juno Gateway Service from Service Control Manager..."); } else { _logger.LogInformation("Starting Juno Service. Please stand by..."); } // _robin.SpeakAsync("Starting Juno Service... Please stand by").Wait(); // Start the Oberon Engine var oberonTask = Task.Run(() => _oberonEngine.Run(cancellationToken)); _taskEngines.Add(oberonTask); _logger.LogInformation($"Oberon engine was started at {DateTimeOffset.Now}"); cancellationToken.WaitHandle.WaitOne(500); // Start the Callisto Engine var callistoTask = Task.Run(() => _callistoEngine.Run(cancellationToken)); _taskEngines.Add(callistoTask); _logger.LogInformation($"Callisto engine was started at {DateTimeOffset.Now}"); return(base.StartAsync(cancellationToken)); }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation($"Executing as {(WindowsServiceHelpers.IsWindowsService() ? "windows service" : "console application")}. Working directory is {Directory.GetCurrentDirectory()}"); // Get rid of await warning await Task.Delay(0); _logger.LogInformation($"Waiting for events..."); }
public static IHostBuilder UseContentRootForSingleFile(this IHostBuilder hostBuilder) { if (WindowsServiceHelpers.IsWindowsService()) { using var process = Process.GetCurrentProcess(); var pathToExe = process.MainModule.FileName; hostBuilder = hostBuilder.UseContentRoot(Path.GetDirectoryName(pathToExe)); } return(hostBuilder); }
public LoopHostedService(IServiceProvider serviceProvider, ILogger logger, int refreshIntervalInSeconds) { _serviceProvider = serviceProvider; _logger = logger; _refreshIntervalInSeconds = refreshIntervalInSeconds; if (WindowsServiceHelpers.IsWindowsService()) { _logger.LogInformation("Running as a windows service!"); } }
/// <summary> /// Configures the lifetime of the <see cref="IHost"/> built from <paramref name="services"/> to /// <see cref="WindowsServiceLifetime"/> and enables logging to the event log with the application name as the default source name. /// </summary> /// <remarks> /// This is context aware and will only activate if it detects the process is running /// as a Windows Service. /// </remarks> /// <param name="services"> /// The <see cref="IServiceCollection"/> used to build the <see cref="IHost"/>. /// For example, <see cref="HostApplicationBuilder.Services"/> or the <see cref="IServiceCollection"/> passed to the /// <see cref="IHostBuilder.ConfigureServices(Action{HostBuilderContext, IServiceCollection})"/> callback. /// </param> /// <param name="configure">An <see cref="Action{WindowsServiceLifetimeOptions}"/> to configure the provided <see cref="WindowsServiceLifetimeOptions"/>.</param> /// <returns>The <paramref name="services"/> instance for chaining.</returns> public static IServiceCollection AddWindowsService(this IServiceCollection services, Action <WindowsServiceLifetimeOptions> configure) { ThrowHelper.ThrowIfNull(services); if (WindowsServiceHelpers.IsWindowsService()) { AddWindowsServiceLifetime(services, configure); } return(services); }
/// <summary> /// Configures SimpleMessageBus to use the either the <see cref="WindowsServiceLifetime"/> or the <see cref="ConsoleLifetime"/> depending on the currently-running context. /// </summary> /// <param name="builder">The <see cref="IHostBuilder"/> instance to extend.</param> /// <returns>The <see cref="IHostBuilder"/> instance being configured, for fluent interaction.</returns> public static IHostBuilder UseSimpleMessageBusLifetime(this IHostBuilder builder) { if (WindowsServiceHelpers.IsWindowsService()) { builder.UseWindowsService(); } else { builder.UseConsoleLifetime(); } return(builder); }
private void Setup() { // Enable windows only events if (WindowsServiceHelpers.IsWindowsService()) { #pragma warning disable CA1416 // Validate platform compatibility CanPauseAndContinue = true; CanShutdown = true; CanHandleSessionChangeEvent = true; CanHandlePowerEvent = true; #pragma warning restore CA1416 // Validate platform compatibility } }
/// <summary> /// Sets the host lifetime to <see cref="WindowsServiceLifetime"/> and enables logging to the event log with the application /// name as the default source name. /// </summary> /// <remarks> /// This is context aware and will only activate if it detects the process is running /// as a Windows Service. /// </remarks> /// <param name="hostBuilder">The <see cref="IHostBuilder"/> to operate on.</param> /// <param name="configure">An <see cref="Action{WindowsServiceLifetimeOptions}"/> to configure the provided <see cref="WindowsServiceLifetimeOptions"/>.</param> /// <returns>The <paramref name="hostBuilder"/> instance for chaining.</returns> public static IHostBuilder UseWindowsService(this IHostBuilder hostBuilder, Action <WindowsServiceLifetimeOptions> configure) { ThrowHelper.ThrowIfNull(hostBuilder); if (WindowsServiceHelpers.IsWindowsService()) { hostBuilder.ConfigureServices(services => { AddWindowsServiceLifetime(services, configure); }); } return(hostBuilder); }
private static void ConfigureSerilog(HostBuilderContext context, LoggerConfiguration config) { config .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Information) .ReadFrom.Configuration(context.Configuration) .Enrich.FromLogContext(); if (WindowsServiceHelpers.IsWindowsService()) { config.WriteTo.EventLog("Application", restrictedToMinimumLevel: LogEventLevel.Warning); } }
protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { if (WindowsServiceHelpers.IsWindowsService()) { _logger.LogInformation("Running as window service"); } else { _logger.LogInformation("Not Running as window service"); } await Task.Delay(1000, stoppingToken); } }
protected override async Task ExecuteAsync(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { if (WindowsServiceHelpers.IsWindowsService()) { logger.LogInformation("Worker running as a service at: {time}", DateTimeOffset.Now); } else { logger.LogInformation("Worker running as a console at: {time}", DateTimeOffset.Now); } await Task.Delay(5000, cancellationToken); } }
public static void Main(string[] args) { var builder = WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((context, config) => { }) .ConfigureLogging(logging => { logging.ClearProviders(); logging.AddConsole(); logging.AddEventLog(settings => { settings.LogName = "Application"; settings.SourceName = ApplicationName; settings.MachineName = Environment.MachineName; }); }) .UseNLog() .UseStartup <Startup>() .ConfigureServices(services => { services.AddHostedService <TimedHostedService>(); }); if (WindowsServiceHelpers.IsWindowsService()) { // ReSharper disable once PossibleNullReferenceException var pathToExe = Process.GetCurrentProcess().MainModule.FileName; var pathToContentRoot = Path.GetDirectoryName(pathToExe); builder.UseContentRoot(pathToContentRoot); // ReSharper disable once AssignNullToNotNullAttribute LogManager.LogFactory.SetCandidateConfigFilePaths(new List <string> { $"{Path.Combine(pathToContentRoot, "nlog.config")}" }); var host = builder.Build(); var webHostService = new ExampleWebHostService(host, ApplicationName); ServiceBase.Run(webHostService); } else { NLogBuilder.ConfigureNLog("nlog.config"); LogManager.GetCurrentClassLogger().Info("Application starting"); builder.Build().Run(); // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) LogManager.Shutdown(); } }
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseWindowsService() .ConfigureServices((hostContext, services) => { if (WindowsServiceHelpers.IsWindowsService()) { services.AddSingleton <IHostLifetime, CustomWindowsService>(); } }) .UseConsoleLifetime() .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup <Startup>() .CaptureStartupErrors(true).ConfigureAppConfiguration(config => { config // Used for local settings like connection strings. .AddJsonFile("appsettings.json", true); }) .UseSerilog((hostingContext, loggerConfiguration) => { loggerConfiguration .ReadFrom.Configuration(hostingContext.Configuration) .Enrich.FromLogContext() .Enrich.WithProperty("ApplicationName", typeof(Program).Assembly.GetName().Name) .Enrich.WithProperty("Environment", hostingContext.HostingEnvironment); #if DEBUG // Used to filter out potentially bad data due debugging. // Very useful when doing Seq dashboards and want to remove logs under debugging session. loggerConfiguration.Enrich.WithProperty("DebuggerAttached", Debugger.IsAttached); #endif }); webBuilder.UseUrls("http://:*:9001", "https://:*:9002"); webBuilder.UseIISIntegration(); // webBuilder.UseUrls("http://:" + _appSettings.HttpApiPort); }).ConfigureServices((hostContext, services) => { services.AddSingleton <IBackgroundWorkerServiceOptions, BackgroundWorkerServiceOptions>(); services.AddHostedService <BackgroundWorkerService>(); });
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration((context, config) => { if (WindowsServiceHelpers.IsWindowsService()) { string workingDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); // Environment.CurrentDirectory = workingDirectory; // Directory.SetCurrentDirectory(workingDirectory); config.SetBasePath(workingDirectory); } }) .UseWindowsService() .ConfigureServices((hostContext, services) => { services.AddHostedService <GamesCleanerWorker>(); }) .UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration .ReadFrom.Configuration(hostingContext.Configuration));
public static ApplicationModes GetApplicationMode(IStartupContext startupContext) { if (startupContext.Help) { return(ApplicationModes.Help); } if (OsInfo.IsWindows && startupContext.RegisterUrl) { return(ApplicationModes.RegisterUrl); } if (OsInfo.IsWindows && startupContext.InstallService) { return(ApplicationModes.InstallService); } if (OsInfo.IsWindows && startupContext.UninstallService) { return(ApplicationModes.UninstallService); } Logger.Debug("Getting windows service status"); // IsWindowsService can throw sometimes, so wrap it var isWindowsService = false; try { isWindowsService = WindowsServiceHelpers.IsWindowsService(); } catch (Exception e) { Logger.Error(e, "Failed to get service status"); } if (OsInfo.IsWindows && isWindowsService) { return(ApplicationModes.Service); } return(ApplicationModes.Interactive); }
public static int Main(string[] args) { var processRoot = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); var contentRoot = WindowsServiceHelpers.IsWindowsService() ? processRoot : Directory.GetCurrentDirectory(); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Information) .MinimumLevel.Override("Microsoft.AspNetCore", Serilog.Events.LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.AspNetCore.SpaServices", Serilog.Events.LogEventLevel.Information) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.RollingFile(Path.Combine(processRoot, "logs\\Butterfly-server.txt"), fileSizeLimitBytes: 10 * 1024 * 1024) .CreateLogger(); Log.Information("----------------------------------------------------------------------"); var assemblyName = Assembly.GetExecutingAssembly().GetName(); var fileInfo = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location); Log.Information($"{assemblyName.Name} v{fileInfo.ProductVersion}"); try { CreateHostBuilder(args, contentRoot) .UseWindowsService() .Build().Run(); return(0); } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception ex) #pragma warning restore CA1031 // Do not catch general exception types { Log.Fatal(ex, "Host terminated unexpectedly."); return(1); } finally { Log.CloseAndFlush(); } }
public static string GetServiceName() { string serviceName = string.Empty; if (WindowsServiceHelpers.IsWindowsService()) { // We install the service in folder named // by the registered service name. So just get the folder name and assume it is the // service name string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); DirectoryInfo dir_info = new DirectoryInfo(directoryName); serviceName = dir_info.Name; } else { serviceName = Process.GetCurrentProcess().ProcessName; } return(serviceName); }
public static void Main(string[] args) { System.IO.Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(Configuration) .CreateLogger(); var host = CreateHostBuilder(args).Build(); var logger = host.Services.GetRequiredService <ILogger <Program> >(); logger.LogInformation("Host built."); logger.LogInformation("App is Windows Service: {IsWinService}", WindowsServiceHelpers.IsWindowsService()); logger.LogInformation("Environment is {EnvName}", host.Services.GetRequiredService <IHostEnvironment>().EnvironmentName); host.Run(); Log.CloseAndFlush(); }
private static Logger CreateLogger(string[] args) { var environment = GetEnvironment(); var configuration = GetConfiguration(); var basePath = GetBasePath(); var outputTemplate = "{Timestamp:HH:mm:ss.fff} [{Level:u4}] {ThreadName}#{ThreadId:000} ({SourceContext}) {Message}{NewLine}{Exception}"; return(new LoggerConfiguration() .WriteTo.Async(asyncConfig => { asyncConfig.Debug(outputTemplate: outputTemplate); asyncConfig.Console(outputTemplate: outputTemplate); asyncConfig.File( path: Path.Join(basePath, "logs\\Bidirectional.Demo.Server.-.log"), outputTemplate: outputTemplate, retainedFileCountLimit: 3, rollingInterval: RollingInterval.Day, rollOnFileSizeLimit: false, shared: true ); }, bufferSize: 100_000, blockWhenFull: true) .ReadFrom.Configuration(configuration) .Enrich.FromLogContext() .Enrich.WithMachineName() .Enrich.WithThreadId() .Enrich.WithThreadName() .CreateLogger()); string GetEnvironment() { return(new ConfigurationBuilder() .AddCommandLine(args) .AddEnvironmentVariables() .Build() .GetValue <string>("Environment") ?? ( DebugDetector.AreWeInDebugMode ? Environments.Development : Environments.Production )); } IConfigurationRoot GetConfiguration() { return(new ConfigurationBuilder() .SetBasePath(GetBasePath()) .AddJsonFile("appsettings.json", reloadOnChange: true, optional: false) .AddJsonFile($"appsettings.{environment}.json", reloadOnChange: true, optional: true) .AddJsonFile($"appsettings.{Environment.MachineName}.json", reloadOnChange: true, optional: true) .AddCommandLine(args) .AddEnvironmentVariables() .Build()); } string GetBasePath() { // When running as a Windows Service, the current directory will be C:\Windows\System32, so we must switch to the assembly directory return(WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : Directory.GetCurrentDirectory()); } }
public static IHostBuilder CreateHostBuilder(string[] args) { return(Host.CreateDefaultBuilder(args) .UseWindowsService() .ConfigureAppConfiguration((context, confiApp) => { // if the app is starting from the Service Control Manager, we // must set the Current Directory so it is not pointing to "Windows/System..." if (WindowsServiceHelpers.IsWindowsService()) { var processModule = Process.GetCurrentProcess().MainModule; if (processModule != null) { var pathToExe = processModule.FileName; var pathToContentRoot = Path.GetDirectoryName(pathToExe); Directory.SetCurrentDirectory(pathToContentRoot); } } confiApp.SetBasePath(Directory.GetCurrentDirectory()); confiApp.AddJsonFile("appsettings.json", optional: false); confiApp.AddEnvironmentVariables(); confiApp.AddCommandLine(args); // NOTE: define process level environment variable if we don't want to bother // with accessing the Azure Key vault: var env = Environment.GetEnvironmentVariable("NETCORE_ENVIRONMENT"); if (env == "Development") { // Console.WriteLine("Adding user secrets file..."); confiApp.AddUserSecrets(typeof(Program).Assembly); } else { //here we use pre-defined app identity to get the secrets from the Azure Key vault //Note: Must run Visual Studio with Admin privileges to access these env variables Log.Information("Attempting to read device keys from Azure Key vault!"); var appClientId = Environment.GetEnvironmentVariable("OceanlabAppIdentityClientId"); var appClientSecret = Environment.GetEnvironmentVariable("OceanlabAppIdentityClientSecret"); if (appClientId == null || appClientSecret == null) { throw new Exception("Unable to Access Azure Key Vault!"); } var kvc = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(async(string authority, string resource, string scope) => { var authContext = new AuthenticationContext(authority); var credential = new ClientCredential(appClientId, appClientSecret); AuthenticationResult result = await authContext.AcquireTokenAsync(resource, credential); if (result == null) { throw new InvalidOperationException("Failed to retrieve key Vault access token"); } return result.AccessToken; })); confiApp.AddAzureKeyVault("https://kalypso.vault.azure.net/", kvc, new DefaultKeyVaultSecretManager()); } }) .ConfigureServices((context, services) => { services.AddOptions(); services.Configure <AppSettings>(context.Configuration); services.AddHostedService <Worker>() .AddSingleton(typeof(OberonEngine)) // NOTE: DI fails to resolve two dependencies of the same type .AddSingleton(typeof(CallistoEngine)) // so this is just a work around .AddSingleton <IAppSettings, AppSettings>() .AddSingleton <ISecureSettings, SecureSettings>(); // .AddSingleton<IRobin, Robin>(); }) .UseSerilog()); }
static void Main(string[] args) { var runningAsService = WindowsServiceHelpers.IsWindowsService(); var configuration = new ConfigurationBuilder() .AddCommandLine(args) .Build(); var serviceConfig = configuration.Get <ServiceConfig>() ?? new ServiceConfig(); var fileProvider = new PhysicalFileProvider(serviceConfig.WorkingDirectory); var loggerConfiguration = new LoggerConfiguration() .WriteTo.File(fileProvider.GetFileInfo(serviceConfig.LogFileName).PhysicalPath); if (runningAsService) { loggerConfiguration.WriteTo.EventLog(GetServiceName()); } else { loggerConfiguration.WriteTo.Console(); } if (Debugger.IsAttached) { loggerConfiguration.WriteTo.Debug(); } var services = new ServiceCollection() .AddLogging(l => l.AddSerilog(loggerConfiguration.CreateLogger(), true)) .AddSingleton <IConfiguration>(configuration) .AddSingleton <IFileProvider>(fileProvider) .BuildServiceProvider(); var logger = services.GetService <ILogger <Program> >(); logger.LogInformation("Creating service wrapper..."); var serverWrapper = new ServerWrapper(services); if (runningAsService) { logger.LogInformation("Starting wrapper in {0} mode.", "service"); ServiceBase.Run(serverWrapper); } else { logger.LogInformation("Starting wrapper in {0} mode.", "console"); new Thread(serverWrapper.Start).Start(); new Thread(_ => { var key = new ConsoleKeyInfo(); logger.LogInformation("Press CTRL + X to exit gracefully."); logger.LogWarning("Press CTRL + C to terminate."); while (key.Modifiers != ConsoleModifiers.Control || key.Key != ConsoleKey.X) { key = Console.ReadKey(true); } serverWrapper.Stop(); }).Start(); } serverWrapper.WaitForExit(); logger.LogInformation("Shutting down."); }
public static void Main(string[] args) { if ((args.Length >= 1 && args[0].Equals("serve", StringComparison.CurrentCulture)) || WindowsServiceHelpers.IsWindowsService()) { RunWebServer(args.Where(a => !string.Equals("serve", a, StringComparison.InvariantCultureIgnoreCase)).ToArray()); } else { Help(); } }