Add: binding setting file items to `AppSettings` class so to provide DI access as `IOptions<OptixServeSettings>`. Add: EF Core and DbContext to access database in services. This results in disabling NativeAOT due to poor supports for *pre-compiled query*, however many design are optimized for AOT for later re-adoption. Add: `DesignTimeDbContextFactory` to support EF Core migrations in NativeAOT. (Kept for re-enabling AOT.) Add: `DbInitializer` for ensuring database connecting in startup. Add: `ConfigurationHelper.CreateDefaultBuilder()` to read configuration files in default locations. Note this method is currently ONLY used by `DesignTimeDbContextFactory`. Refactor is expected. Add: `CommonErrorDto` for simple error message. Add: `VersionEndpoint` ONLY for debugging and testing purpose. Verylikely to be removed in the future. Other: many utilities and fixes easy to understand. Note: EF Core migrations are excluded in the early development. Not expected to be added in version control before v1.0 beta.
155 lines
5.6 KiB
C#
155 lines
5.6 KiB
C#
using System.CommandLine;
|
|
using OptixServe.Api.Configuration;
|
|
using OptixServe.Api.Endpoints;
|
|
using OptixServe.Core.Data;
|
|
using OptixServe.Core.Services;
|
|
using OptixServe.Api.Utilites;
|
|
|
|
class Program
|
|
{
|
|
/// <summary>
|
|
/// Main method that configures and runs the application
|
|
/// </summary>
|
|
/// <param name="args">Command line arguments</param>
|
|
/// <returns>A Task representing the asynchronous operation</returns>
|
|
static async Task Main(string[] args)
|
|
{
|
|
var rootCommand = new RootCommand("OptixServe API");
|
|
|
|
// Configure the --config/-c command line option
|
|
var configOption = new Option<FileInfo?>("--config", "-c")
|
|
{
|
|
Description = "Config file path",
|
|
CustomParser = arg =>
|
|
{
|
|
if (!arg.Tokens.Any()) return null;
|
|
|
|
var filePath = arg.Tokens.Single().Value;
|
|
if (!File.Exists(filePath))
|
|
{
|
|
arg.AddError($"Configuration file not found: {filePath}");
|
|
return null;
|
|
}
|
|
return new FileInfo(filePath);
|
|
}
|
|
};
|
|
rootCommand.Add(configOption);
|
|
|
|
// Set handle for rootCommand
|
|
// The handle prototype and way of parsing arguments
|
|
// is changed in System.CommandLine 2.0.0-beta5
|
|
rootCommand.SetAction((ParseResult parseResult) =>
|
|
{
|
|
var builder = WebApplication.CreateSlimBuilder(args);
|
|
|
|
var configFile = parseResult.GetValue(configOption);
|
|
builder.AddConfigurationWithCommand(configFile);
|
|
|
|
builder.RegisterServices();
|
|
builder.RegiserJsonContext();
|
|
|
|
var app = builder.Build();
|
|
|
|
using (var scope = app.Services.CreateScope())
|
|
{
|
|
var initializer = scope.ServiceProvider.GetRequiredService<DbInitializer>();
|
|
initializer.Initialize();
|
|
}
|
|
|
|
var apiGroup = app.MapGroup("api/v1");
|
|
StartupHelper.RegisterEndpoints(apiGroup);
|
|
|
|
app.Run();
|
|
});
|
|
|
|
// Parse arguments then invoke the command
|
|
var parseResult = rootCommand.Parse(args);
|
|
await parseResult.InvokeAsync();
|
|
}
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// Contains extension methods for WebApplicationBuilder and WebApplication
|
|
/// </summary>
|
|
static class StartupHelper
|
|
{
|
|
/// <summary>
|
|
/// Adds configuration sources to the application builder
|
|
/// </summary>
|
|
/// <param name="builder">WebApplicationBuilder instance</param>
|
|
/// <param name="file">Optional configuration file specified via command line</param>
|
|
public static void AddConfigurationWithCommand(this WebApplicationBuilder builder, FileInfo? file)
|
|
{
|
|
// Configure configuration sources in specified order
|
|
var configurationBuilder = new ConfigurationBuilder()
|
|
.SetBasePath(Directory.GetCurrentDirectory())
|
|
.AddJsonFile("appsettings.json", optional: true)
|
|
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true)
|
|
.AddJsonFile("config.json", optional: true)
|
|
.AddJsonFile($"config.{builder.Environment.EnvironmentName}.json", optional: true);
|
|
|
|
// Add command-line specified config file if provided
|
|
if (file != null)
|
|
{
|
|
configurationBuilder.AddJsonFile(file.FullName, optional: false);
|
|
}
|
|
|
|
builder.Configuration.AddConfiguration(configurationBuilder.Build());
|
|
}
|
|
|
|
/// <summary>
|
|
/// Configures DbContext services
|
|
/// </summary>
|
|
/// <param name="services"></param>
|
|
/// <param name="configuration"></param>
|
|
/// <returns></returns>
|
|
public static IServiceCollection AddAppDatabase(this IServiceCollection services, DatabaseSettings dbSettings)
|
|
{
|
|
services.AddDbContext<AppDbContext>(options => DatabaseHelper.ConfigureDbContext(options, dbSettings));
|
|
return services;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Configures services for DI
|
|
/// </summary>
|
|
/// <param name="builder">WebApplicationBuilder instance</param>
|
|
public static void RegisterServices(this WebApplicationBuilder builder)
|
|
{
|
|
// Add configuration class
|
|
var optixSettigns = builder.Configuration.GetSection("OptixServe");
|
|
var onConfigSettings = optixSettigns.Get<OptixServeSettings>();
|
|
builder.Services.Configure<OptixServeSettings>(optixSettigns);
|
|
|
|
// Add DBContext class
|
|
builder.Services.AddAppDatabase(onConfigSettings?.Database!);
|
|
builder.Services.AddScoped<DbInitializer>();
|
|
|
|
// Application services
|
|
builder.Services.AddScoped<IUserService, UserService>();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Configures JSON serialization options with custom context
|
|
/// </summary>
|
|
/// <param name="builder">WebApplicationBuilder instance</param>
|
|
public static void RegiserJsonContext(this WebApplicationBuilder builder)
|
|
{
|
|
builder.Services.ConfigureHttpJsonOptions(options =>
|
|
{
|
|
options.SerializerOptions.TypeInfoResolverChain.Add(UserJsonContext.Default);
|
|
options.SerializerOptions.TypeInfoResolverChain.Add(VersionJsonContext.Default);
|
|
});
|
|
}
|
|
|
|
/// <summary>
|
|
/// Registers all API endpoints
|
|
/// </summary>
|
|
/// <param name="rootGroup">Root RouteGroupBuilder instance</param>
|
|
public static void RegisterEndpoints(RouteGroupBuilder rootGroup)
|
|
{
|
|
UserEndpoint.Register(rootGroup);
|
|
VersionEndpoint.Register(rootGroup);
|
|
}
|
|
|
|
} |