80 lines
2.2 KiB
C#
80 lines
2.2 KiB
C#
|
|
using Newtonsoft.Json;
|
||
|
|
|
||
|
|
namespace Bitget_Server.Infrastructure.Utils;
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// JSON 파일에 자동 영속화되는 싱글톤 설정 베이스.
|
||
|
|
/// 기존 WinForms BaseSettings<T> 로직을 유지하되, ASP.NET Core 환경에서는
|
||
|
|
/// 파일 저장 경로를 /data 볼륨(컨테이너) 또는 AppContext.BaseDirectory로 사용한다.
|
||
|
|
/// </summary>
|
||
|
|
public class BaseSettings<T> where T : class, new()
|
||
|
|
{
|
||
|
|
private static readonly object lockObject = new object();
|
||
|
|
private static readonly object fileLockObject = new object();
|
||
|
|
private static T _instance;
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// 설정 파일을 저장할 디렉토리. Program.cs에서 시작 시 지정한다 (기본: AppContext.BaseDirectory).
|
||
|
|
/// </summary>
|
||
|
|
public static string StorageDirectory { get; set; } = AppContext.BaseDirectory;
|
||
|
|
|
||
|
|
public static T Instance
|
||
|
|
{
|
||
|
|
get
|
||
|
|
{
|
||
|
|
lock (lockObject)
|
||
|
|
{
|
||
|
|
if (_instance == null)
|
||
|
|
_instance = CreateInstance();
|
||
|
|
}
|
||
|
|
return _instance;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
protected static T CreateInstance()
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var saveFilePath = GetFilePath();
|
||
|
|
if (File.Exists(saveFilePath))
|
||
|
|
{
|
||
|
|
return JsonConvert.DeserializeObject<T>(File.ReadAllText(saveFilePath)) ?? new T();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
catch
|
||
|
|
{
|
||
|
|
// 손상 시 기본값으로 복구
|
||
|
|
}
|
||
|
|
return new T();
|
||
|
|
}
|
||
|
|
|
||
|
|
private static string GetFilePath()
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
Directory.CreateDirectory(StorageDirectory);
|
||
|
|
}
|
||
|
|
catch { }
|
||
|
|
return Path.Combine(StorageDirectory, typeof(T).Name + ".json");
|
||
|
|
}
|
||
|
|
|
||
|
|
public void SaveConfig()
|
||
|
|
{
|
||
|
|
lock (fileLockObject)
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
string json = JsonConvert.SerializeObject(this, Formatting.Indented);
|
||
|
|
File.WriteAllText(GetFilePath(), json);
|
||
|
|
}
|
||
|
|
catch
|
||
|
|
{
|
||
|
|
// 저장 실패는 무시 (로그는 상위 레이어에서)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <summary>SaveConfig 의 짧은 별칭.</summary>
|
||
|
|
public void Save() => SaveConfig();
|
||
|
|
}
|