InventoryAgent/Inventory.Agent/Program.cs
2025-10-21 12:58:33 +08:00

80 lines
3.7 KiB
C#

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<string, string>(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<InventoryContext>(options => options.UseSqlServer(dbCon));
services.AddHostedService<Worker>();
services.AddHttpClient();
services.AddSingleton<SystemInfoCollector>(provider =>
{
var collector = new SystemInfoCollector();
collector.Consumer = ConsumerType.Agent; // Explicitly set the consumer
return collector;
});
services.AddScoped<DatabaseUpdater>(provider => new DatabaseUpdater(
provider.GetRequiredService<InventoryContext>(),
provider.GetRequiredService<SystemInfoCollector>(),
provider.GetRequiredService<HealthMonitor>(),
ConsumerType.Agent
));
services.AddScoped<HealthMonitor>();
services.AddScoped<SlurpitClient>(); // No longer needs collector/monitor
services.AddScoped<UpdateWorkflow>(provider => new UpdateWorkflow(
provider.GetRequiredService<DatabaseUpdater>(),
provider.GetRequiredService<SystemInfoCollector>(),
provider.GetRequiredService<InventoryContext>(),
provider.GetRequiredService<SlurpitClient>()
));
});
}
}