Add configuration type binding and implement database connection, disable NativeAOT.
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.
This commit is contained in:
25
OptixServe.Api/Configuration/AppSettings.cs
Normal file
25
OptixServe.Api/Configuration/AppSettings.cs
Normal file
@ -0,0 +1,25 @@
|
||||
namespace OptixServe.Api.Configuration;
|
||||
|
||||
public record OptixServeSettings
|
||||
{
|
||||
public ApiSettings? Api { get; set; } = new();
|
||||
public DatabaseSettings? Database { get; set; } = new();
|
||||
}
|
||||
|
||||
public record ApiSettings
|
||||
{
|
||||
public string? Listen { get; set; } = "127.0.0.1";
|
||||
public int? Port { get; set; } = 10086;
|
||||
}
|
||||
|
||||
public enum DatabaseType
|
||||
{
|
||||
Sqlite,
|
||||
MySQL
|
||||
}
|
||||
|
||||
public record DatabaseSettings
|
||||
{
|
||||
public DatabaseType Type { get; set; } = DatabaseType.Sqlite;
|
||||
public string? Host { get; set; }
|
||||
}
|
27
OptixServe.Api/Configuration/ConfigurationHelper.cs
Normal file
27
OptixServe.Api/Configuration/ConfigurationHelper.cs
Normal file
@ -0,0 +1,27 @@
|
||||
using System;
|
||||
|
||||
namespace OptixServe.Api.Configuration;
|
||||
|
||||
public static class ConfigurationHelper
|
||||
{
|
||||
public static IConfigurationBuilder CreateDefaultBuilder()
|
||||
{
|
||||
var aspEnv = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
|
||||
var netEnv = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
|
||||
// Console.WriteLine($"ASPNETCORE_ENVIRONMENT: {aspEnv}, DOTNET_ENVIRONMENT: {netEnv}");
|
||||
var env = aspEnv ?? netEnv ?? null;
|
||||
|
||||
var builder = new ConfigurationBuilder()
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile("appsettings.json", optional: true)
|
||||
.AddJsonFile("config.json", optional: true);
|
||||
|
||||
if (env != null)
|
||||
{
|
||||
builder.AddJsonFile($"appsettings.{env}.json", optional: true)
|
||||
.AddJsonFile($"config.{env}.json", optional: true);
|
||||
}
|
||||
|
||||
return builder;
|
||||
}
|
||||
}
|
6
OptixServe.Api/Dtos/Error.cs
Normal file
6
OptixServe.Api/Dtos/Error.cs
Normal file
@ -0,0 +1,6 @@
|
||||
namespace OptixServe.Api.Dtos;
|
||||
|
||||
public record CommonErrorDto
|
||||
{
|
||||
public string? Message { get; set; }
|
||||
}
|
35
OptixServe.Api/Endpoints/VersionEndpoint.cs
Normal file
35
OptixServe.Api/Endpoints/VersionEndpoint.cs
Normal file
@ -0,0 +1,35 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using Microsoft.Extensions.Options;
|
||||
using OptixServe.Api.Configuration;
|
||||
using OptixServe.Api.Dtos;
|
||||
|
||||
namespace OptixServe.Api.Endpoints;
|
||||
|
||||
|
||||
[JsonSerializable(typeof(string))]
|
||||
[JsonSerializable(typeof(CommonErrorDto))]
|
||||
public partial class VersionJsonContext : JsonSerializerContext { }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// This is a endpoint ONLY FOR TEST!
|
||||
/// Should not expect ANY stable behavior on it!
|
||||
/// </summary>
|
||||
public static class VersionEndpoint
|
||||
{
|
||||
public static void Register(RouteGroupBuilder parentGroup)
|
||||
{
|
||||
var group = parentGroup.MapGroup("/version");
|
||||
|
||||
group.MapGet("/", () => "v1");
|
||||
group.MapGet("/test/dbconfig", (IOptions<OptixServeSettings> appSettings) =>
|
||||
{
|
||||
var dbType = appSettings.Value.Database?.Type;
|
||||
var dbHost = appSettings.Value.Database?.Host;
|
||||
return Results.Ok(new CommonErrorDto
|
||||
{
|
||||
Message = $"Set up {dbType} database on {dbHost}"
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
@ -1,11 +1,16 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\OptixServe.Core\OptixServe.Core.csproj" />
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\OptixServe.Core\OptixServe.Core.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="System.CommandLine" Version="2.0.0-beta5.25306.1" />
|
||||
<ItemGroup>
|
||||
<PackageReference Include="System.CommandLine" Version="2.0.0-beta5.25306.1" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.6">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="9.0.6" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
@ -13,7 +18,7 @@
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<PublishAot>true</PublishAot>
|
||||
<PublishAot>false</PublishAot>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
|
@ -1,6 +1,9 @@
|
||||
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
|
||||
{
|
||||
@ -46,8 +49,15 @@ class Program
|
||||
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");
|
||||
ExtensionMethods.RegisterEndpoints(apiGroup);
|
||||
StartupHelper.RegisterEndpoints(apiGroup);
|
||||
|
||||
app.Run();
|
||||
});
|
||||
@ -62,7 +72,7 @@ class Program
|
||||
/// <summary>
|
||||
/// Contains extension methods for WebApplicationBuilder and WebApplication
|
||||
/// </summary>
|
||||
static class ExtensionMethods
|
||||
static class StartupHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// Adds configuration sources to the application builder
|
||||
@ -88,6 +98,37 @@ static class ExtensionMethods
|
||||
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>
|
||||
@ -97,26 +138,18 @@ static class ExtensionMethods
|
||||
builder.Services.ConfigureHttpJsonOptions(options =>
|
||||
{
|
||||
options.SerializerOptions.TypeInfoResolverChain.Add(UserJsonContext.Default);
|
||||
options.SerializerOptions.TypeInfoResolverChain.Add(VersionJsonContext.Default);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures services for DI
|
||||
/// </summary>
|
||||
/// <param name="builder"></param>
|
||||
public static void RegisterServices(this WebApplicationBuilder builder)
|
||||
{
|
||||
// Application services
|
||||
builder.Services.AddScoped<IUserService, UserService>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers all API endpoints
|
||||
/// </summary>
|
||||
/// <param name="app">WebApplication instance</param>
|
||||
/// <param name="rootGroup">Root RouteGroupBuilder instance</param>
|
||||
public static void RegisterEndpoints(RouteGroupBuilder rootGroup)
|
||||
{
|
||||
UserEndpoint.Register(rootGroup);
|
||||
VersionEndpoint.Register(rootGroup);
|
||||
}
|
||||
|
||||
}
|
34
OptixServe.Api/Utilites/DatabaseHelper.cs
Normal file
34
OptixServe.Api/Utilites/DatabaseHelper.cs
Normal file
@ -0,0 +1,34 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using OptixServe.Api.Configuration;
|
||||
using OptixServe.Core.Data;
|
||||
|
||||
namespace OptixServe.Api.Utilites;
|
||||
|
||||
public static class DatabaseHelper
|
||||
{
|
||||
public static string BuildConnectionString(DatabaseSettings dbSettings)
|
||||
{
|
||||
return dbSettings.Type switch
|
||||
{
|
||||
DatabaseType.Sqlite => $"Data Source={dbSettings.Host ?? "optixserve.db"}",
|
||||
DatabaseType.MySQL => throw new NotSupportedException("MySQL connection is not yet implemented"),
|
||||
_ => throw new NotSupportedException($"Database type {dbSettings.Type} is not supported")
|
||||
};
|
||||
}
|
||||
|
||||
public static void ConfigureDbContext(DbContextOptionsBuilder options, DatabaseSettings dbSettings)
|
||||
{
|
||||
if (dbSettings?.Type == DatabaseType.Sqlite)
|
||||
{
|
||||
var dbPath = dbSettings.Host ?? "optixserve.db";
|
||||
var connectionString = $"Data Source={dbPath}";
|
||||
|
||||
options.UseSqlite(connectionString, b => b.MigrationsAssembly("OptixServe.Api"));
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NotImplementedException("Only SQLite database is currently supported");
|
||||
}
|
||||
}
|
||||
}
|
20
OptixServe.Api/Utilites/DesignTimeDbContextFactory.cs
Normal file
20
OptixServe.Api/Utilites/DesignTimeDbContextFactory.cs
Normal file
@ -0,0 +1,20 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Design;
|
||||
using OptixServe.Api.Configuration;
|
||||
using OptixServe.Core.Data;
|
||||
|
||||
namespace OptixServe.Api.Utilites;
|
||||
|
||||
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
|
||||
{
|
||||
public AppDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
var configuration = ConfigurationHelper.CreateDefaultBuilder().Build();
|
||||
|
||||
var dbSettings = configuration.GetSection("OptixServe:Database").Get<DatabaseSettings>()!;
|
||||
var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
|
||||
DatabaseHelper.ConfigureDbContext(optionsBuilder, dbSettings);
|
||||
|
||||
return new AppDbContext(optionsBuilder.Options);
|
||||
}
|
||||
}
|
@ -5,5 +5,15 @@
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
"AllowedHosts": "*",
|
||||
"OptixServe": {
|
||||
"Api": {
|
||||
"Listen": "0.0.0.0",
|
||||
"Port": "54321"
|
||||
},
|
||||
"Database": {
|
||||
"Type": "Sqlite",
|
||||
"Host": "optixserve.db"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
21
OptixServe.Core/Data/AppDbContext.cs
Normal file
21
OptixServe.Core/Data/AppDbContext.cs
Normal file
@ -0,0 +1,21 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using OptixServe.Core.Models;
|
||||
|
||||
namespace OptixServe.Core.Data;
|
||||
|
||||
public class AppDbContext(DbContextOptions options) : DbContext(options)
|
||||
{
|
||||
public DbSet<User> Users { get; set; } = null!;
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<User>(user =>
|
||||
{
|
||||
user.HasKey(u => u.Id);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<User>().HasData([
|
||||
new() {Id = "1", UserName = "admin", Password = "admin12345"}
|
||||
]);
|
||||
}
|
||||
}
|
11
OptixServe.Core/Data/DbInitializer.cs
Normal file
11
OptixServe.Core/Data/DbInitializer.cs
Normal file
@ -0,0 +1,11 @@
|
||||
namespace OptixServe.Core.Data;
|
||||
|
||||
public class DbInitializer(AppDbContext dbContext)
|
||||
{
|
||||
private readonly AppDbContext _context = dbContext;
|
||||
|
||||
public void Initialize()
|
||||
{
|
||||
_context.Database.EnsureCreated();
|
||||
}
|
||||
}
|
@ -1,8 +1,15 @@
|
||||
namespace OptixServe.Core.Models;
|
||||
|
||||
public enum PrivilegeGroup
|
||||
{
|
||||
Admin,
|
||||
User,
|
||||
}
|
||||
|
||||
public record User
|
||||
{
|
||||
public required string Id { get; set; }
|
||||
public required string UserName { get; set; }
|
||||
public required string Password { get; set; }
|
||||
public string? Password { get; set; }
|
||||
public PrivilegeGroup PrivilegeGroup { get; set; } = PrivilegeGroup.User;
|
||||
}
|
@ -6,4 +6,8 @@
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.6" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
@ -1,3 +1,4 @@
|
||||
using OptixServe.Core.Data;
|
||||
using OptixServe.Core.Models;
|
||||
|
||||
namespace OptixServe.Core.Services;
|
||||
@ -5,21 +6,20 @@ namespace OptixServe.Core.Services;
|
||||
public interface IUserService
|
||||
{
|
||||
IEnumerable<User> GetUsers();
|
||||
User? GetUserById(string Id);
|
||||
User? GetUserById(string id);
|
||||
}
|
||||
|
||||
public class UserService : IUserService
|
||||
public class UserService(AppDbContext dbContext) : IUserService
|
||||
{
|
||||
public User? GetUserById(string Id)
|
||||
private readonly AppDbContext _dbContext = dbContext;
|
||||
|
||||
public User? GetUserById(string id)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
return _dbContext.Users.FirstOrDefault(u => u.Id == id);
|
||||
}
|
||||
|
||||
public IEnumerable<User> GetUsers()
|
||||
{
|
||||
return [
|
||||
new() { Id = "1234", UserName = "xxx", Password = "pass1" },
|
||||
new() { Id = "5678", UserName = "yyy", Password = "pass2" }
|
||||
];
|
||||
return _dbContext.Users.AsEnumerable();
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user