Jelajahi Sumber

Configuration for persistence

Lukas Angerer 3 tahun lalu
induk
melakukan
47bce1de34

+ 6 - 3
src/RunnersMeet.Server/AppServer.cs

@@ -8,7 +8,7 @@ public class AppServer
 	{
 		var builder = WebApplication.CreateBuilder(args);
 
-		ConfigureServices(builder.Services);
+		ConfigureServices(builder.Services, builder.Configuration);
 		builder.Services.AddControllers();
 		// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
 		builder.Services.AddEndpointsApiExplorer();
@@ -32,9 +32,12 @@ public class AppServer
 		app.Run();
 	}
 
-	private void ConfigureServices(IServiceCollection services)
+	private void ConfigureServices(IServiceCollection services, IConfigurationRoot config)
 	{
-		services.AddSingleton<IDatabase>(new Database());
+		services.AddSingleton<IDatabase, Database>();
 		services.AddScoped<QueryFactory, QueryFactory>();
+
+		services.Configure<PersistenceOptions>(config.GetSection(PersistenceOptions.Persistence));
+		services.AddTransient<IPersistenceOptions, PersistenceOptionsAccessor>();
 	}
 }

+ 2 - 2
src/RunnersMeet.Server/Persistence/Database.cs

@@ -9,9 +9,9 @@ public class Database : IDatabase
 
 	public ILiteCollection<Track> Tracks { get; }
 
-	public Database()
+	public Database(IPersistenceOptions persistenceOptions)
 	{
-		_db = new LiteDatabase(@"./data/tracks.db");
+		_db = new LiteDatabase(persistenceOptions.DataFilePath);
 
 		Tracks = _db.GetCollection<Track>("tracks");
 		Tracks.EnsureIndex(t => t.FileName);

+ 32 - 0
src/RunnersMeet.Server/PersistenceOptions.cs

@@ -0,0 +1,32 @@
+using Microsoft.Extensions.Options;
+
+namespace RunnersMeet.Server;
+
+public interface IPersistenceOptions
+{
+	string DataFilePath { get; }
+	string FileStorageRootPath { get; }
+}
+
+public class PersistenceOptions : IPersistenceOptions
+{
+	public const string Persistence = "Persistence";
+
+	public string DataFilePath { get; set; } = String.Empty;
+	public string FileStorageRootPath { get; set; } = String.Empty;
+}
+
+public class PersistenceOptionsAccessor : IPersistenceOptions
+{
+	private readonly PersistenceOptions _options;
+	private readonly IHostEnvironment _env;
+
+	public PersistenceOptionsAccessor(IOptions<PersistenceOptions> options, IHostEnvironment env)
+	{
+		_options = options.Value;
+		_env = env;
+	}
+
+	public string DataFilePath => Path.Join(_env.ContentRootPath, _options.DataFilePath);
+	public string FileStorageRootPath => Path.Join(_env.ContentRootPath, _options.FileStorageRootPath);
+}

+ 11 - 7
src/RunnersMeet.Server/appsettings.json

@@ -1,9 +1,13 @@
 {
-  "Logging": {
-    "LogLevel": {
-      "Default": "Information",
-      "Microsoft.AspNetCore": "Warning"
-    }
-  },
-  "AllowedHosts": "*"
+	"Logging": {
+		"LogLevel": {
+			"Default": "Information",
+			"Microsoft.AspNetCore": "Warning"
+		}
+	},
+	"AllowedHosts": "*",
+	"Persistence": {
+		"DataFilePath": "./data/tracks.db",
+		"FileStorageRootPath": "./data/files"
+	}
 }