using System; using System.IO; using System.Reflection; using Inventory.Core; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Inventory.Agent { public class Program { public static void Main(string[] args) { // Set the current directory to the application's base directory. // This ensures that files like .env are found correctly when running as a service. Directory.SetCurrentDirectory(AppContext.BaseDirectory); CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseWindowsService() // Important for running as a Windows Service .ConfigureHostConfiguration(config => { #if DEBUG config.AddInMemoryCollection(new[] { new KeyValuePair(HostDefaults.EnvironmentKey, "Development") }); #endif }) .ConfigureLogging(logging => { // Configure logging providers for the service logging.ClearProviders(); logging.AddEventLog(); // Log to Windows Event Viewer logging.AddConsole(); // Also log to console for debugging }) .ConfigureAppConfiguration((context, config) => { // Setup secrets here, after the default configuration and environment are established. EnvironmentBuilder.SetupEnvironment(context.HostingEnvironment); }) .ConfigureServices((hostContext, services) => { var dbCon = Secrets.DbConnectionString; if (string.IsNullOrWhiteSpace(dbCon)) { // This will now correctly log to the Event Viewer if the .env file is missing or misconfigured. throw new InvalidOperationException("FATAL ERROR: DB_CONNECTION_STRING is not configured. The service cannot start."); } services.AddDbContext(options => options.UseSqlServer(dbCon)); services.AddHostedService(); services.AddHttpClient(); services.AddSingleton(provider => { var collector = new SystemInfoCollector(); collector.Consumer = ConsumerType.Agent; // Explicitly set the consumer return collector; }); services.AddScoped(provider => new DatabaseUpdater( provider.GetRequiredService(), provider.GetRequiredService(), provider.GetRequiredService(), ConsumerType.Agent )); services.AddScoped(); services.AddScoped(); // No longer needs collector/monitor services.AddScoped(provider => new UpdateWorkflow( provider.GetRequiredService(), provider.GetRequiredService(), provider.GetRequiredService(), provider.GetRequiredService() )); }); } }