ServiceCollectionExtensions.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.IO;
  3. using Microsoft.Extensions.Configuration;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using Microsoft.Extensions.Options;
  6. using Newtonsoft.Json;
  7. using Newtonsoft.Json.Linq;
  8. namespace Team.Utility
  9. {
  10. public class WritableOptions<T> : IWritableOptions<T> where T : class, new()
  11. {
  12. private readonly IOptionsMonitor<T> _options;
  13. private readonly string _section;
  14. private readonly string _file;
  15. public WritableOptions(IOptionsMonitor<T> options, string section, string file)
  16. {
  17. _options = options;
  18. _section = section;
  19. _file = file;
  20. }
  21. public T Value => _options.CurrentValue;
  22. public T Get(string name) => _options.Get(name);
  23. public void Update(Action<T> applyChanges)
  24. {
  25. var physicalPath =Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _file);
  26. var jObject = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(physicalPath));
  27. var sectionObject = jObject.TryGetValue(_section, out var section) ?
  28. JsonConvert.DeserializeObject<T>(section.ToString()) : Value ?? new T();
  29. applyChanges(sectionObject);
  30. jObject[_section] = JObject.Parse(JsonConvert.SerializeObject(sectionObject));
  31. File.WriteAllText(physicalPath, JsonConvert.SerializeObject(jObject, Formatting.Indented),System.Text.Encoding.UTF8);
  32. }
  33. }
  34. public static class ServiceCollectionExtensions
  35. {
  36. public static void ConfigureWritable<T>(
  37. this IServiceCollection services,
  38. IConfigurationSection section,
  39. string file = "appsettings.json") where T : class, new()
  40. {
  41. services.Configure<T>(section);
  42. services.AddSingleton<IWritableOptions<T>>(provider =>
  43. {
  44. var options = provider.GetService<IOptionsMonitor<T>>();
  45. return new WritableOptions<T>(options, section.Key, file); });
  46. }
  47. }
  48. }