YamlDotNet을 이용한 설정 클래스

메타데이터를 관리하기 위해 요즘에는 XML보다는 JSON을 많이 사용하는데요, 유사하게 YAML이라는 형태가 있습니다. 아래 글을 참고 바라구요,

저는 .NET에서 YAML을 쓸 수 있도록 해주는 YamlDotNet를 이용해 설정 정보를 파일로 쉽게 읽고 쓰는 클래스를 만들어 보았습니다.

    public abstract class Settings<T>
        where T : Settings<T>, new()
    {
        private static readonly IDeserializer deserializer = new DeserializerBuilder()
            .WithNamingConvention(UnderscoredNamingConvention.Instance)
            .IgnoreFields()
            .Build();
        private static readonly ISerializer serializer = new SerializerBuilder()
            .WithNamingConvention(UnderscoredNamingConvention.Instance)
            .IgnoreFields()
            .Build();


        [YamlIgnore]
        public string Filepath { get; private set; }


        protected Settings()
        {
        }

        public static T Load(string filepath)
        {
            if (File.Exists(filepath) == false)
                return new T { Filepath = filepath };

            var yamlText = File.ReadAllText(filepath);
            var result = deserializer.Deserialize<T>(yamlText);
            result.Filepath = filepath;

            return result;
        }

        public void Save()
        {
            var directory = Path.GetDirectoryName(Filepath);
            if (Directory.Exists(directory) == false)
                Directory.CreateDirectory(directory);

            var yamlText = serializer.Serialize(this);
            File.WriteAllText(Filepath, yamlText);
        }
    }

그리고 사용은,

    public class AppSettings : Settings<AppSettings>
    {
        public AppTheme Theme { get; set; }

        public static string RootPath { get; } = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        public static string SettingsPath { get; } = Path.Combine(RootPath, "settings", "settings.yaml");
    }

    public enum AppTheme
    {
        Light,
        Dark
    }
...
private AppSettings Settings { get; } = AppSettings.Load(AppSettings.SettingsPath);
...

        private void SetTheme(AppTheme theme)
        {
            if (theme == AppTheme.Light)
            {
                ThemeManager.Current.ApplicationTheme = ApplicationTheme.Light;
                dockManager.Theme = LightTheme;
            }
            else // if (themeKind == ThemeKind.Dark)
            {
                ThemeManager.Current.ApplicationTheme = ApplicationTheme.Dark;
                dockManager.Theme = DarkTheme;
            }

            Settings.Theme = theme;
            Settings.Save();
        }

이런 식으로 사용할 수 있습니다 :slight_smile:

3개의 좋아요

@dimohy 좋은 설명 감사드립니다. :smile:
저도 구조 참고해서 제가 작업한 부분도 한번 남겨볼게요.

2개의 좋아요