using System.CommandLine;
using OptixServe.Api.Endpoints;
class Program
{
///
/// Main method that configures and runs the application
///
/// Command line arguments
/// A Task representing the asynchronous operation
static async Task Main(string[] args)
{
var rootCommand = new RootCommand("OptixServe API");
// Configure the --config/-c command line option
var configOption = new Option("--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.RegiserJsonContext();
var app = builder.Build();
app.RegisterEndpoints();
app.Run();
});
// Parse arguments then invoke the command
var parseResult = rootCommand.Parse(args);
await parseResult.InvokeAsync();
}
}
///
/// Contains extension methods for WebApplicationBuilder and WebApplication
///
static class ExtensionMethods
{
///
/// Registers all API endpoints
///
/// WebApplication instance
public static void RegisterEndpoints(this WebApplication app)
{
UserEndpoint.Register(app);
}
///
/// Configures JSON serialization options with custom context
///
/// WebApplicationBuilder instance
public static void RegiserJsonContext(this WebApplicationBuilder builder)
{
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Add(UserJsonContext.Default);
});
}
///
/// Adds configuration sources to the application builder
///
/// WebApplicationBuilder instance
/// Optional configuration file specified via command line
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());
}
}