Files
TriliumMind/Program.cs

100 lines
3.7 KiB
C#

using Microsoft.EntityFrameworkCore;
using Serilog;
using System.Threading.Channels;
using TriliumMind.Data;
using TriliumMind.Models;
using TriliumMind.Services;
using TriliumMind.Workers;
namespace TriliumMind
{
public class Program
{
public static async Task Main(string[] args)
{
var builder = Host.CreateApplicationBuilder(args);
// Configure AppSettings
var env = builder.Environment.EnvironmentName;
builder.Configuration
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.AddCommandLine(args);
builder.Services.Configure<AppSettings>(builder.Configuration);
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();
// Register Config class (must be registered before DbContext)
builder.Services.AddSingleton<AppConfigs>();
// Register DbContext based on configuration
builder.Services.AddScoped<IAppDbContext>(sp =>
{
var appConfigs = sp.GetRequiredService<AppConfigs>();
var dbType = appConfigs.AppSettings.Database.Type;
Log.Information("Configuring database type: {DbType}", dbType);
return dbType.ToLower() switch
{
"postgres" => new PostgresDbContext(appConfigs),
"sqlite" => new SqliteDbContext(appConfigs),
_ => throw new InvalidOperationException($"Unsupported database type: {dbType}")
};
});
// Register Services
builder.Services.AddSingleton<JiraService>();
builder.Services.AddSingleton<TriliumService>();
builder.Services.AddScoped<AppDbService>();
// Register Workers
builder.Services.AddHostedService<JiraWorker>();
builder.Services.AddHostedService<TriliumWorker>();
builder.Services.AddHostedService<AppDbWorker>();
// Register Channels
builder.Services.AddSingleton(Channel.CreateUnbounded<Issue>());
var host = builder.Build();
try
{
Log.Information("Starting database migration...");
using var scope = host.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<IAppDbContext>();
if(dbContext is DbContext context)
{
var created = await context.Database.EnsureCreatedAsync();
if(created)
Log.Information("Database created successfully");
else
Log.Information("Database already exists");
}
var dbService = scope.ServiceProvider.GetRequiredService<AppDbService>();
var appCoinfigs = host.Services.GetRequiredService<AppConfigs>();
appCoinfigs.RuntimeConfigs = await dbService.LoadConfigAsync();
Log.Information("Database initialization completed successfully");
}
catch (Exception ex)
{
Log.Fatal(ex, "Database migration failed. Application cannot start without a valid database connection.");
Log.CloseAndFlush();
Environment.Exit(1);
}
host.Run();
}
}
}