Refactor
This commit is contained in:
@@ -1,4 +1,3 @@
|
|||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
{
|
|
||||||
public record ConfigurationChanged<TConfiguration>(TConfiguration Configuration) where TConfiguration : class;
|
public record ConfigurationChanged<TConfiguration>(TConfiguration Configuration) where TConfiguration : class;
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,23 +1,22 @@
|
|||||||
using Mediator;
|
using Mediator;
|
||||||
|
|
||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
|
|
||||||
|
public class ConfigurationInitializer<TConfiguration> : IInitializable where TConfiguration : class, new()
|
||||||
{
|
{
|
||||||
public class ConfigurationInitializer<TConfiguration> : IInitializer where TConfiguration : class, new()
|
private readonly TConfiguration configuration;
|
||||||
|
private readonly IMediator mediator;
|
||||||
|
|
||||||
|
public ConfigurationInitializer(TConfiguration configuration,
|
||||||
|
IMediator mediator)
|
||||||
{
|
{
|
||||||
private readonly TConfiguration configuration;
|
this.configuration = configuration;
|
||||||
private readonly IMediator mediator;
|
this.mediator = mediator;
|
||||||
|
}
|
||||||
|
|
||||||
public ConfigurationInitializer(TConfiguration configuration,
|
public async Task InitializeAsync()
|
||||||
IMediator mediator)
|
{
|
||||||
{
|
await mediator.Send(configuration);
|
||||||
this.configuration = configuration;
|
await Task.CompletedTask;
|
||||||
this.mediator = mediator;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task InitializeAsync()
|
|
||||||
{
|
|
||||||
await mediator.Send(configuration);
|
|
||||||
await Task.CompletedTask;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,30 +2,28 @@
|
|||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
|
|
||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
|
|
||||||
|
public class ConfigurationWriter<TConfiguration> : IConfigurationWriter<TConfiguration> where TConfiguration : class, new()
|
||||||
{
|
{
|
||||||
public class ConfigurationWriter<TConfiguration> : IConfigurationWriter<TConfiguration> where TConfiguration : class, new()
|
private readonly IConfiguration rootConfiguration;
|
||||||
|
|
||||||
|
public ConfigurationWriter(IConfiguration rootConfiguration)
|
||||||
{
|
{
|
||||||
private readonly IConfiguration rootConfiguration;
|
this.rootConfiguration = rootConfiguration;
|
||||||
|
}
|
||||||
|
|
||||||
public ConfigurationWriter(IConfiguration rootConfiguration)
|
public void Write(string section, TConfiguration configuration)
|
||||||
|
{
|
||||||
|
if (rootConfiguration is IConfigurationRoot root)
|
||||||
{
|
{
|
||||||
this.rootConfiguration = rootConfiguration;
|
foreach (IConfigurationProvider? provider in root.Providers)
|
||||||
}
|
|
||||||
|
|
||||||
public void Write(string section, TConfiguration configuration)
|
|
||||||
{
|
|
||||||
if (rootConfiguration is IConfigurationRoot root)
|
|
||||||
{
|
{
|
||||||
foreach (IConfigurationProvider? provider in root.Providers)
|
if (provider is IWritableConfigurationProvider writableConfigurationProvider)
|
||||||
{
|
{
|
||||||
if (provider is IWritableConfigurationProvider writableConfigurationProvider)
|
writableConfigurationProvider.Write(section, configuration);
|
||||||
{
|
|
||||||
writableConfigurationProvider.Write(section, configuration);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
{
|
|
||||||
public interface IConfigurationWriter<TConfiguration> where TConfiguration : class
|
|
||||||
{
|
|
||||||
void Write(string section, TConfiguration args);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
public interface IConfigurationWriter<TConfiguration> where TConfiguration : class
|
||||||
|
{
|
||||||
|
void Write(string section, TConfiguration args);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
{
|
|
||||||
public interface IWritableConfigurationProvider
|
|
||||||
{
|
|
||||||
void Write<TValue>(string section, TValue value) where TValue : class, new();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
public interface IWritableConfigurationProvider
|
||||||
|
{
|
||||||
|
void Write<TValue>(string section, TValue value) where TValue : class, new();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,12 @@
|
|||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
|
|
||||||
|
public interface IWritableJsonConfigurationBuilder
|
||||||
{
|
{
|
||||||
public interface IWritableJsonConfigurationBuilder
|
Stream? DefaultFileStream { get; }
|
||||||
{
|
|
||||||
Stream? DefaultFileStream { get; }
|
|
||||||
|
|
||||||
IWritableJsonConfigurationBuilder AddDefaultConfiguration<TConfiguration>(string Key) where TConfiguration : class;
|
IWritableJsonConfigurationBuilder AddDefaultConfiguration<TConfiguration>(string Key) where TConfiguration : class;
|
||||||
|
|
||||||
IWritableJsonConfigurationBuilder AddDefaultFileStream(Stream stream);
|
IWritableJsonConfigurationBuilder AddDefaultFileStream(Stream stream);
|
||||||
|
|
||||||
void Build(string path);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
void Build(string path);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
|
|
||||||
|
public interface IWritableJsonConfigurationDescriptor
|
||||||
{
|
{
|
||||||
public interface IWritableJsonConfigurationDescriptor
|
Type ConfigurationType { get; }
|
||||||
{
|
|
||||||
Type ConfigurationType { get; }
|
|
||||||
|
|
||||||
string Key { get; }
|
|
||||||
}
|
|
||||||
|
|
||||||
|
string Key { get; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,101 +10,99 @@ using System.Text.Json;
|
|||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
using JsonSerializer = System.Text.Json.JsonSerializer;
|
using JsonSerializer = System.Text.Json.JsonSerializer;
|
||||||
|
|
||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
|
|
||||||
|
public class WritableJsonConfigurationBuilder : IWritableJsonConfigurationBuilder
|
||||||
{
|
{
|
||||||
public class WritableJsonConfigurationBuilder : IWritableJsonConfigurationBuilder
|
private readonly List<IWritableJsonConfigurationDescriptor> descriptors = new();
|
||||||
|
|
||||||
|
public Stream? DefaultFileStream { get; private set; }
|
||||||
|
|
||||||
|
public IReadOnlyCollection<IWritableJsonConfigurationDescriptor> Descriptors => new ReadOnlyCollection<IWritableJsonConfigurationDescriptor>(descriptors);
|
||||||
|
|
||||||
|
public IWritableJsonConfigurationBuilder AddDefaultConfiguration<TConfiguration>(string Key) where TConfiguration : class
|
||||||
{
|
{
|
||||||
private readonly List<IWritableJsonConfigurationDescriptor> descriptors = new();
|
descriptors.Add(new WritableJsonConfigurationDescriptor(typeof(TConfiguration), Key));
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
public Stream? DefaultFileStream { get; private set; }
|
public IWritableJsonConfigurationBuilder AddDefaultFileStream(Stream stream)
|
||||||
|
{
|
||||||
|
DefaultFileStream = stream;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
public IReadOnlyCollection<IWritableJsonConfigurationDescriptor> Descriptors => new ReadOnlyCollection<IWritableJsonConfigurationDescriptor>(descriptors);
|
public void Build(string path)
|
||||||
|
{
|
||||||
public IWritableJsonConfigurationBuilder AddDefaultConfiguration<TConfiguration>(string Key) where TConfiguration : class
|
JObject? sourceDocument = new();
|
||||||
|
if (TryLoadSource(out string? defaultContent))
|
||||||
{
|
{
|
||||||
descriptors.Add(new WritableJsonConfigurationDescriptor(typeof(TConfiguration), Key));
|
sourceDocument = JObject.Parse(defaultContent!);
|
||||||
return this;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public IWritableJsonConfigurationBuilder AddDefaultFileStream(Stream stream)
|
JObject? targetDocument = new();
|
||||||
|
if (TryLoadTarget(path, out string? targetContent))
|
||||||
{
|
{
|
||||||
DefaultFileStream = stream;
|
targetDocument = JObject.Parse(targetContent!);
|
||||||
return this;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Build(string path)
|
foreach (IWritableJsonConfigurationDescriptor? descriptor in descriptors)
|
||||||
{
|
{
|
||||||
JObject? sourceDocument = new();
|
if (sourceDocument.SelectToken($"$.{descriptor.Key}") is JToken sourceSection)
|
||||||
if (TryLoadSource(out string? defaultContent))
|
|
||||||
{
|
{
|
||||||
sourceDocument = JObject.Parse(defaultContent!);
|
if (targetDocument.SelectToken($"$.{descriptor.Key}") is JToken targetSection)
|
||||||
}
|
|
||||||
|
|
||||||
JObject? targetDocument = new();
|
|
||||||
if (TryLoadTarget(path, out string? targetContent))
|
|
||||||
{
|
|
||||||
targetDocument = JObject.Parse(targetContent!);
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (IWritableJsonConfigurationDescriptor? descriptor in descriptors)
|
|
||||||
{
|
|
||||||
if (sourceDocument.SelectToken($"$.{descriptor.Key}") is JToken sourceSection)
|
|
||||||
{
|
{
|
||||||
if (targetDocument.SelectToken($"$.{descriptor.Key}") is JToken targetSection)
|
object? source = JsonSerializer.Deserialize(JsonConvert.SerializeObject(sourceSection), descriptor.ConfigurationType);
|
||||||
{
|
object? target = JsonSerializer.Deserialize(JsonConvert.SerializeObject(targetSection), descriptor.ConfigurationType);
|
||||||
object? source = JsonSerializer.Deserialize(JsonConvert.SerializeObject(sourceSection), descriptor.ConfigurationType);
|
|
||||||
object? target = JsonSerializer.Deserialize(JsonConvert.SerializeObject(targetSection), descriptor.ConfigurationType);
|
|
||||||
|
|
||||||
JsonPatch? patch = source.CreatePatch(target);
|
JsonPatch? patch = source.CreatePatch(target);
|
||||||
|
|
||||||
object? sourcePatched = patch.Apply(source);
|
object? sourcePatched = patch.Apply(source);
|
||||||
targetSection.Replace(JToken.Parse(JsonSerializer.Serialize(sourcePatched, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull })));
|
targetSection.Replace(JToken.Parse(JsonSerializer.Serialize(sourcePatched, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull })));
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
object? source = JsonSerializer.Deserialize(JsonConvert.SerializeObject(sourceSection), descriptor.ConfigurationType);
|
|
||||||
targetDocument.Add(descriptor.Key, JToken.Parse(JsonSerializer.Serialize(source, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull })));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
object? configuration = Activator.CreateInstance(descriptor.ConfigurationType);
|
object? source = JsonSerializer.Deserialize(JsonConvert.SerializeObject(sourceSection), descriptor.ConfigurationType);
|
||||||
targetDocument.Add(descriptor.Key, JToken.Parse(JsonSerializer.Serialize(configuration, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull })));
|
targetDocument.Add(descriptor.Key, JToken.Parse(JsonSerializer.Serialize(source, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull })));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
else
|
||||||
using FileStream? fileStream = new(path, FileMode.Create, FileAccess.Write);
|
|
||||||
using StreamWriter streamWriter = new(fileStream);
|
|
||||||
using JsonTextWriter writer = new(streamWriter) { Formatting = Formatting.Indented };
|
|
||||||
targetDocument.WriteTo(writer);
|
|
||||||
}
|
|
||||||
|
|
||||||
private bool TryLoadTarget(string path, [MaybeNull] out string? content)
|
|
||||||
{
|
|
||||||
if (File.Exists(path))
|
|
||||||
{
|
{
|
||||||
using FileStream? fileStream = new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
object? configuration = Activator.CreateInstance(descriptor.ConfigurationType);
|
||||||
using StreamReader? streamReader = new(fileStream);
|
targetDocument.Add(descriptor.Key, JToken.Parse(JsonSerializer.Serialize(configuration, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull })));
|
||||||
content = streamReader.ReadToEnd();
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
content = null;
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool TryLoadSource([MaybeNull] out string? content)
|
using FileStream? fileStream = new(path, FileMode.Create, FileAccess.Write);
|
||||||
{
|
using StreamWriter streamWriter = new(fileStream);
|
||||||
if (DefaultFileStream is Stream fileStream)
|
using JsonTextWriter writer = new(streamWriter) { Formatting = Formatting.Indented };
|
||||||
{
|
targetDocument.WriteTo(writer);
|
||||||
using StreamReader? streamReader = new(fileStream);
|
|
||||||
content = streamReader.ReadToEnd();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
content = null;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private bool TryLoadTarget(string path, [MaybeNull] out string? content)
|
||||||
|
{
|
||||||
|
if (File.Exists(path))
|
||||||
|
{
|
||||||
|
using FileStream? fileStream = new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||||
|
using StreamReader? streamReader = new(fileStream);
|
||||||
|
content = streamReader.ReadToEnd();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
content = null;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool TryLoadSource([MaybeNull] out string? content)
|
||||||
|
{
|
||||||
|
if (DefaultFileStream is Stream fileStream)
|
||||||
|
{
|
||||||
|
using StreamReader? streamReader = new(fileStream);
|
||||||
|
content = streamReader.ReadToEnd();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
content = null;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
{
|
|
||||||
public record WritableJsonConfigurationDescriptor(Type ConfigurationType, string Key) : IWritableJsonConfigurationDescriptor;
|
|
||||||
|
|
||||||
}
|
public record WritableJsonConfigurationDescriptor(Type ConfigurationType, string Key) : IWritableJsonConfigurationDescriptor;
|
||||||
|
|||||||
@@ -1,76 +1,74 @@
|
|||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.FileProviders;
|
using Microsoft.Extensions.FileProviders;
|
||||||
|
|
||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
|
|
||||||
|
public static class WritableJsonConfigurationExtensions
|
||||||
{
|
{
|
||||||
public static class WritableJsonConfigurationExtensions
|
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
|
||||||
|
string path)
|
||||||
{
|
{
|
||||||
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
|
return builder.AddWritableJsonFile(null, path, false, false, null);
|
||||||
string path)
|
|
||||||
{
|
|
||||||
return builder.AddWritableJsonFile(null, path, false, false, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
|
|
||||||
string path,
|
|
||||||
Action<IWritableJsonConfigurationBuilder>? factoryDelegate)
|
|
||||||
{
|
|
||||||
return builder.AddWritableJsonFile(null, path, false, false, factoryDelegate);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
|
|
||||||
string path,
|
|
||||||
bool optional)
|
|
||||||
{
|
|
||||||
return builder.AddWritableJsonFile(null, path, optional, false, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
|
|
||||||
string path,
|
|
||||||
bool optional,
|
|
||||||
Action<IWritableJsonConfigurationBuilder>? factoryDelegate)
|
|
||||||
{
|
|
||||||
return builder.AddWritableJsonFile(null, path, optional, false, factoryDelegate);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
|
|
||||||
string path,
|
|
||||||
bool optional,
|
|
||||||
bool reloadOnChange)
|
|
||||||
{
|
|
||||||
return builder.AddWritableJsonFile(null, path, optional, reloadOnChange, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
|
|
||||||
string path,
|
|
||||||
bool optional,
|
|
||||||
bool reloadOnChange,
|
|
||||||
Action<IWritableJsonConfigurationBuilder>? factoryDelegate)
|
|
||||||
{
|
|
||||||
return builder.AddWritableJsonFile(null, path, optional, reloadOnChange, factoryDelegate);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
|
|
||||||
IFileProvider? provider,
|
|
||||||
string path,
|
|
||||||
bool optional,
|
|
||||||
bool reloadOnChange, Action<IWritableJsonConfigurationBuilder>? writableJsonConfigurationDelegate)
|
|
||||||
{
|
|
||||||
IWritableJsonConfigurationBuilder writableJsonConfigurationBuilder = new WritableJsonConfigurationBuilder();
|
|
||||||
writableJsonConfigurationDelegate?.Invoke(writableJsonConfigurationBuilder);
|
|
||||||
|
|
||||||
return builder.AddWritableJsonFile(configuration =>
|
|
||||||
{
|
|
||||||
configuration.FileProvider = provider;
|
|
||||||
configuration.Path = path;
|
|
||||||
configuration.Optional = optional;
|
|
||||||
configuration.ReloadOnChange = reloadOnChange;
|
|
||||||
configuration.Factory = writableJsonConfigurationBuilder;
|
|
||||||
configuration.ResolveFileProvider();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder, Action<WritableJsonConfigurationSource> configureSource) => builder.Add(configureSource);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
|
||||||
|
string path,
|
||||||
|
Action<IWritableJsonConfigurationBuilder>? factoryDelegate)
|
||||||
|
{
|
||||||
|
return builder.AddWritableJsonFile(null, path, false, false, factoryDelegate);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
|
||||||
|
string path,
|
||||||
|
bool optional)
|
||||||
|
{
|
||||||
|
return builder.AddWritableJsonFile(null, path, optional, false, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
|
||||||
|
string path,
|
||||||
|
bool optional,
|
||||||
|
Action<IWritableJsonConfigurationBuilder>? factoryDelegate)
|
||||||
|
{
|
||||||
|
return builder.AddWritableJsonFile(null, path, optional, false, factoryDelegate);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
|
||||||
|
string path,
|
||||||
|
bool optional,
|
||||||
|
bool reloadOnChange)
|
||||||
|
{
|
||||||
|
return builder.AddWritableJsonFile(null, path, optional, reloadOnChange, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
|
||||||
|
string path,
|
||||||
|
bool optional,
|
||||||
|
bool reloadOnChange,
|
||||||
|
Action<IWritableJsonConfigurationBuilder>? factoryDelegate)
|
||||||
|
{
|
||||||
|
return builder.AddWritableJsonFile(null, path, optional, reloadOnChange, factoryDelegate);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder,
|
||||||
|
IFileProvider? provider,
|
||||||
|
string path,
|
||||||
|
bool optional,
|
||||||
|
bool reloadOnChange, Action<IWritableJsonConfigurationBuilder>? writableJsonConfigurationDelegate)
|
||||||
|
{
|
||||||
|
IWritableJsonConfigurationBuilder writableJsonConfigurationBuilder = new WritableJsonConfigurationBuilder();
|
||||||
|
writableJsonConfigurationDelegate?.Invoke(writableJsonConfigurationBuilder);
|
||||||
|
|
||||||
|
return builder.AddWritableJsonFile(configuration =>
|
||||||
|
{
|
||||||
|
configuration.FileProvider = provider;
|
||||||
|
configuration.Path = path;
|
||||||
|
configuration.Optional = optional;
|
||||||
|
configuration.ReloadOnChange = reloadOnChange;
|
||||||
|
configuration.Factory = writableJsonConfigurationBuilder;
|
||||||
|
configuration.ResolveFileProvider();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IConfigurationBuilder AddWritableJsonFile(this IConfigurationBuilder builder, Action<WritableJsonConfigurationSource> configureSource) => builder.Add(configureSource);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,148 +3,146 @@ using Newtonsoft.Json;
|
|||||||
using Newtonsoft.Json.Linq;
|
using Newtonsoft.Json.Linq;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
|
||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
|
|
||||||
|
internal class WritableJsonConfigurationFile
|
||||||
{
|
{
|
||||||
internal class WritableJsonConfigurationFile
|
private readonly Dictionary<string, (JsonValueKind?, string?)> data = new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
private readonly Stack<string> paths = new();
|
||||||
|
private JObject tokenCache = new();
|
||||||
|
private bool isParsing;
|
||||||
|
|
||||||
|
public IDictionary<string, string?> Parse(Stream input)
|
||||||
{
|
{
|
||||||
private readonly Dictionary<string, (JsonValueKind?, string?)> data = new(StringComparer.OrdinalIgnoreCase);
|
return ParseStream(input);
|
||||||
private readonly Stack<string> paths = new();
|
}
|
||||||
private JObject tokenCache = new();
|
|
||||||
private bool isParsing;
|
|
||||||
|
|
||||||
public IDictionary<string, string?> Parse(Stream input)
|
public void Write(string key, string value, Stream output)
|
||||||
|
{
|
||||||
|
if (isParsing)
|
||||||
{
|
{
|
||||||
return ParseStream(input);
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Write(string key, string value, Stream output)
|
if (key[^1] == ':')
|
||||||
{
|
{
|
||||||
if (isParsing)
|
key = key[0..^1];
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (key[^1] == ':')
|
|
||||||
{
|
|
||||||
key = key[0..^1];
|
|
||||||
}
|
|
||||||
|
|
||||||
string? tokenPath = $"$.{key.Replace(":", ".")}";
|
|
||||||
key = key.Replace("[", "").Replace("]", "");
|
|
||||||
|
|
||||||
if (tokenCache.SelectToken(tokenPath) is JToken token && data.ContainsKey(key))
|
|
||||||
{
|
|
||||||
(JsonValueKind? kind, string _) = data[key];
|
|
||||||
object? newValue = ConvertValue(kind, value);
|
|
||||||
|
|
||||||
data[key] = new(kind, value);
|
|
||||||
token.Replace(JToken.FromObject(newValue));
|
|
||||||
}
|
|
||||||
|
|
||||||
using StreamWriter streamWriter = new(output);
|
|
||||||
using JsonTextWriter writer = new(streamWriter) { Formatting = Formatting.Indented };
|
|
||||||
tokenCache.WriteTo(writer);
|
|
||||||
|
|
||||||
output.SetLength(output.Position);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static object ConvertValue(JsonValueKind? kind, string value)
|
string? tokenPath = $"$.{key.Replace(":", ".")}";
|
||||||
|
key = key.Replace("[", "").Replace("]", "");
|
||||||
|
|
||||||
|
if (tokenCache.SelectToken(tokenPath) is JToken token && data.ContainsKey(key))
|
||||||
{
|
{
|
||||||
return kind is JsonValueKind.True or JsonValueKind.False ? bool.Parse(value) : value;
|
(JsonValueKind? kind, string _) = data[key];
|
||||||
|
object? newValue = ConvertValue(kind, value);
|
||||||
|
|
||||||
|
data[key] = new(kind, value);
|
||||||
|
token.Replace(JToken.FromObject(newValue));
|
||||||
}
|
}
|
||||||
|
|
||||||
private void EnterContext(string context)
|
using StreamWriter streamWriter = new(output);
|
||||||
|
using JsonTextWriter writer = new(streamWriter) { Formatting = Formatting.Indented };
|
||||||
|
tokenCache.WriteTo(writer);
|
||||||
|
|
||||||
|
output.SetLength(output.Position);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static object ConvertValue(JsonValueKind? kind, string value)
|
||||||
|
{
|
||||||
|
return kind is JsonValueKind.True or JsonValueKind.False ? bool.Parse(value) : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EnterContext(string context)
|
||||||
|
{
|
||||||
|
paths.Push(paths.Count > 0 ? paths.Peek() + ConfigurationPath.KeyDelimiter + context : context);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ExitContext()
|
||||||
|
{
|
||||||
|
paths.Pop();
|
||||||
|
}
|
||||||
|
|
||||||
|
private IDictionary<string, string?> ParseStream(Stream input)
|
||||||
|
{
|
||||||
|
data.Clear();
|
||||||
|
|
||||||
|
JsonDocumentOptions jsonDocumentOptions = new()
|
||||||
{
|
{
|
||||||
paths.Push(paths.Count > 0 ? paths.Peek() + ConfigurationPath.KeyDelimiter + context : context);
|
CommentHandling = JsonCommentHandling.Skip,
|
||||||
|
AllowTrailingCommas = true,
|
||||||
|
};
|
||||||
|
|
||||||
|
isParsing = true;
|
||||||
|
using (StreamReader? reader = new(input))
|
||||||
|
{
|
||||||
|
string? content = reader.ReadToEnd();
|
||||||
|
tokenCache = JObject.Parse(content);
|
||||||
|
|
||||||
|
using JsonDocument? doc = JsonDocument.Parse(content, jsonDocumentOptions);
|
||||||
|
VisitElement(doc.RootElement);
|
||||||
|
}
|
||||||
|
isParsing = false;
|
||||||
|
|
||||||
|
return data.ToDictionary(k => k.Key, v => v.Value.Item2?.ToString() ?? null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void VisitElement(JsonElement element)
|
||||||
|
{
|
||||||
|
bool isEmpty = true;
|
||||||
|
|
||||||
|
foreach (JsonProperty property in element.EnumerateObject())
|
||||||
|
{
|
||||||
|
isEmpty = false;
|
||||||
|
|
||||||
|
EnterContext(property.Name);
|
||||||
|
VisitValue(property.Value);
|
||||||
|
ExitContext();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ExitContext()
|
if (isEmpty && paths.Count > 0)
|
||||||
{
|
{
|
||||||
paths.Pop();
|
data[paths.Peek()] = (JsonValueKind.Null, null);
|
||||||
}
|
|
||||||
|
|
||||||
private IDictionary<string, string?> ParseStream(Stream input)
|
|
||||||
{
|
|
||||||
data.Clear();
|
|
||||||
|
|
||||||
JsonDocumentOptions jsonDocumentOptions = new()
|
|
||||||
{
|
|
||||||
CommentHandling = JsonCommentHandling.Skip,
|
|
||||||
AllowTrailingCommas = true,
|
|
||||||
};
|
|
||||||
|
|
||||||
isParsing = true;
|
|
||||||
using (StreamReader? reader = new(input))
|
|
||||||
{
|
|
||||||
string? content = reader.ReadToEnd();
|
|
||||||
tokenCache = JObject.Parse(content);
|
|
||||||
|
|
||||||
using JsonDocument? doc = JsonDocument.Parse(content, jsonDocumentOptions);
|
|
||||||
VisitElement(doc.RootElement);
|
|
||||||
}
|
|
||||||
isParsing = false;
|
|
||||||
|
|
||||||
return data.ToDictionary(k => k.Key, v => v.Value.Item2?.ToString() ?? null);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void VisitElement(JsonElement element)
|
|
||||||
{
|
|
||||||
bool isEmpty = true;
|
|
||||||
|
|
||||||
foreach (JsonProperty property in element.EnumerateObject())
|
|
||||||
{
|
|
||||||
isEmpty = false;
|
|
||||||
|
|
||||||
EnterContext(property.Name);
|
|
||||||
VisitValue(property.Value);
|
|
||||||
ExitContext();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isEmpty && paths.Count > 0)
|
|
||||||
{
|
|
||||||
data[paths.Peek()] = (JsonValueKind.Null, null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void VisitValue(JsonElement value)
|
|
||||||
{
|
|
||||||
switch (value.ValueKind)
|
|
||||||
{
|
|
||||||
case JsonValueKind.Object:
|
|
||||||
VisitElement(value);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case JsonValueKind.Array:
|
|
||||||
int index = 0;
|
|
||||||
foreach (JsonElement arrayElement in value.EnumerateArray())
|
|
||||||
{
|
|
||||||
EnterContext(index.ToString());
|
|
||||||
VisitValue(arrayElement);
|
|
||||||
ExitContext();
|
|
||||||
index++;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
|
|
||||||
case JsonValueKind.Number:
|
|
||||||
case JsonValueKind.String:
|
|
||||||
case JsonValueKind.True:
|
|
||||||
case JsonValueKind.False:
|
|
||||||
case JsonValueKind.Null:
|
|
||||||
string key = paths.Peek();
|
|
||||||
if (data.ContainsKey(key))
|
|
||||||
{
|
|
||||||
throw new FormatException();
|
|
||||||
}
|
|
||||||
data[key] = new(value.ValueKind, value.ToString());
|
|
||||||
break;
|
|
||||||
|
|
||||||
case JsonValueKind.Undefined:
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
throw new FormatException();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void VisitValue(JsonElement value)
|
||||||
|
{
|
||||||
|
switch (value.ValueKind)
|
||||||
|
{
|
||||||
|
case JsonValueKind.Object:
|
||||||
|
VisitElement(value);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case JsonValueKind.Array:
|
||||||
|
int index = 0;
|
||||||
|
foreach (JsonElement arrayElement in value.EnumerateArray())
|
||||||
|
{
|
||||||
|
EnterContext(index.ToString());
|
||||||
|
VisitValue(arrayElement);
|
||||||
|
ExitContext();
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case JsonValueKind.Number:
|
||||||
|
case JsonValueKind.String:
|
||||||
|
case JsonValueKind.True:
|
||||||
|
case JsonValueKind.False:
|
||||||
|
case JsonValueKind.Null:
|
||||||
|
string key = paths.Peek();
|
||||||
|
if (data.ContainsKey(key))
|
||||||
|
{
|
||||||
|
throw new FormatException();
|
||||||
|
}
|
||||||
|
data[key] = new(value.ValueKind, value.ToString());
|
||||||
|
break;
|
||||||
|
|
||||||
|
case JsonValueKind.Undefined:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
throw new FormatException();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,46 +3,44 @@ using Microsoft.Extensions.FileProviders;
|
|||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using Newtonsoft.Json.Linq;
|
using Newtonsoft.Json.Linq;
|
||||||
|
|
||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
|
|
||||||
|
public class WritableJsonConfigurationProvider : JsonConfigurationProvider, IWritableConfigurationProvider
|
||||||
{
|
{
|
||||||
public class WritableJsonConfigurationProvider : JsonConfigurationProvider, IWritableConfigurationProvider
|
public WritableJsonConfigurationProvider(JsonConfigurationSource source) : base(source)
|
||||||
{
|
{
|
||||||
public WritableJsonConfigurationProvider(JsonConfigurationSource source) : base(source)
|
|
||||||
{
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Write<TValue>(string section, TValue value) where TValue : class, new()
|
|
||||||
{
|
|
||||||
IFileInfo? file = Source.FileProvider?.GetFileInfo(Source.Path ?? string.Empty);
|
|
||||||
static Stream OpenRead(IFileInfo fileInfo)
|
|
||||||
{
|
|
||||||
return fileInfo.PhysicalPath is not null
|
|
||||||
? new FileStream(fileInfo.PhysicalPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
|
|
||||||
: fileInfo.CreateReadStream();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (file is null)
|
|
||||||
{
|
|
||||||
throw new FileNotFoundException();
|
|
||||||
}
|
|
||||||
|
|
||||||
using Stream stream = OpenRead(file);
|
|
||||||
using StreamReader? reader = new(stream);
|
|
||||||
|
|
||||||
string? content = reader.ReadToEnd();
|
|
||||||
JObject? document = JObject.Parse(content);
|
|
||||||
|
|
||||||
if (document.SelectToken($"$.{section}") is JToken sectionToken)
|
|
||||||
{
|
|
||||||
sectionToken.Replace(JToken.Parse(JsonConvert.SerializeObject(value)));
|
|
||||||
stream.SetLength(0);
|
|
||||||
|
|
||||||
using StreamWriter streamWriter = new(stream);
|
|
||||||
using JsonTextWriter writer = new(streamWriter) { Formatting = Formatting.Indented };
|
|
||||||
document.WriteTo(writer);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void Write<TValue>(string section, TValue value) where TValue : class, new()
|
||||||
|
{
|
||||||
|
IFileInfo? file = Source.FileProvider?.GetFileInfo(Source.Path ?? string.Empty);
|
||||||
|
static Stream OpenRead(IFileInfo fileInfo)
|
||||||
|
{
|
||||||
|
return fileInfo.PhysicalPath is not null
|
||||||
|
? new FileStream(fileInfo.PhysicalPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
|
||||||
|
: fileInfo.CreateReadStream();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (file is null)
|
||||||
|
{
|
||||||
|
throw new FileNotFoundException();
|
||||||
|
}
|
||||||
|
|
||||||
|
using Stream stream = OpenRead(file);
|
||||||
|
using StreamReader? reader = new(stream);
|
||||||
|
|
||||||
|
string? content = reader.ReadToEnd();
|
||||||
|
JObject? document = JObject.Parse(content);
|
||||||
|
|
||||||
|
if (document.SelectToken($"$.{section}") is JToken sectionToken)
|
||||||
|
{
|
||||||
|
sectionToken.Replace(JToken.Parse(JsonConvert.SerializeObject(value)));
|
||||||
|
stream.SetLength(0);
|
||||||
|
|
||||||
|
using StreamWriter streamWriter = new(stream);
|
||||||
|
using JsonTextWriter writer = new(streamWriter) { Formatting = Formatting.Indented };
|
||||||
|
document.WriteTo(writer);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,27 +2,26 @@
|
|||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.FileProviders;
|
using Microsoft.Extensions.FileProviders;
|
||||||
|
|
||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
|
|
||||||
|
public class WritableJsonConfigurationSource : JsonConfigurationSource
|
||||||
{
|
{
|
||||||
public class WritableJsonConfigurationSource : JsonConfigurationSource
|
public IWritableJsonConfigurationBuilder? Factory { get; set; }
|
||||||
|
|
||||||
|
public override IConfigurationProvider Build(IConfigurationBuilder builder)
|
||||||
{
|
{
|
||||||
public IWritableJsonConfigurationBuilder? Factory { get; set; }
|
EnsureDefaultsWithSteam(builder);
|
||||||
|
return new WritableJsonConfigurationProvider(this);
|
||||||
|
}
|
||||||
|
|
||||||
public override IConfigurationProvider Build(IConfigurationBuilder builder)
|
private void EnsureDefaultsWithSteam(IConfigurationBuilder builder)
|
||||||
|
{
|
||||||
|
EnsureDefaults(builder);
|
||||||
|
|
||||||
|
if (FileProvider is PhysicalFileProvider physicalFileProvider)
|
||||||
{
|
{
|
||||||
EnsureDefaultsWithSteam(builder);
|
string? outputFile = System.IO.Path.Combine(physicalFileProvider.Root, Path);
|
||||||
return new WritableJsonConfigurationProvider(this);
|
Factory?.Build(outputFile);
|
||||||
}
|
|
||||||
|
|
||||||
private void EnsureDefaultsWithSteam(IConfigurationBuilder builder)
|
|
||||||
{
|
|
||||||
EnsureDefaults(builder);
|
|
||||||
|
|
||||||
if (FileProvider is PhysicalFileProvider physicalFileProvider)
|
|
||||||
{
|
|
||||||
string? outputFile = System.IO.Path.Combine(physicalFileProvider.Root, Path);
|
|
||||||
Factory?.Build(outputFile);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
using Mediator;
|
using Mediator;
|
||||||
|
|
||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
{
|
|
||||||
public abstract record Write<TConfiguration>(string Section, Action<TConfiguration> UpdateDelegate) : IRequest where TConfiguration : class;
|
public abstract record Write<TConfiguration>(string Section, Action<TConfiguration> UpdateDelegate) : IRequest where TConfiguration : class;
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,30 +1,29 @@
|
|||||||
using Mediator;
|
using Mediator;
|
||||||
|
|
||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
|
|
||||||
|
public class WriteHandler<TConfiguration> : IRequestHandler<Write<TConfiguration>> where TConfiguration : class
|
||||||
{
|
{
|
||||||
public class WriteHandler<TConfiguration> : IRequestHandler<Write<TConfiguration>> where TConfiguration : class
|
private readonly IMediator mediator;
|
||||||
|
private readonly TConfiguration configuration;
|
||||||
|
private readonly IConfigurationWriter<TConfiguration> writer;
|
||||||
|
|
||||||
|
public WriteHandler(TConfiguration configuration,
|
||||||
|
IConfigurationWriter<TConfiguration> writer,
|
||||||
|
IMediator mediator)
|
||||||
{
|
{
|
||||||
private readonly IMediator mediator;
|
this.mediator = mediator;
|
||||||
private readonly TConfiguration configuration;
|
this.configuration = configuration;
|
||||||
private readonly IConfigurationWriter<TConfiguration> writer;
|
this.writer = writer;
|
||||||
|
}
|
||||||
|
|
||||||
public WriteHandler(TConfiguration configuration,
|
public async ValueTask<Unit> Handle(Write<TConfiguration> request, CancellationToken cancellationToken)
|
||||||
IConfigurationWriter<TConfiguration> writer,
|
{
|
||||||
IMediator mediator)
|
request.UpdateDelegate.Invoke(configuration);
|
||||||
{
|
writer.Write(request.Section, configuration);
|
||||||
this.mediator = mediator;
|
|
||||||
this.configuration = configuration;
|
|
||||||
this.writer = writer;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async ValueTask<Unit> Handle(Write<TConfiguration> request, CancellationToken cancellationToken)
|
await mediator.Send(new ConfigurationChanged<TConfiguration>(configuration), cancellationToken);
|
||||||
{
|
|
||||||
request.UpdateDelegate.Invoke(configuration);
|
|
||||||
writer.Write(request.Section, configuration);
|
|
||||||
|
|
||||||
await mediator.Send(new ConfigurationChanged<TConfiguration>(configuration), cancellationToken);
|
return default;
|
||||||
|
|
||||||
return default;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,16 @@
|
|||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
|
|
||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
{
|
|
||||||
public static class IHostBuilderExtensions
|
|
||||||
{
|
|
||||||
public static IHostBuilder UseContentRoot(this IHostBuilder hostBuilder, string contentRoot, bool createDirectory)
|
|
||||||
{
|
|
||||||
if (!Directory.Exists(contentRoot) && createDirectory)
|
|
||||||
{
|
|
||||||
Directory.CreateDirectory(contentRoot);
|
|
||||||
}
|
|
||||||
|
|
||||||
return hostBuilder.UseContentRoot(contentRoot);
|
public static class IHostBuilderExtensions
|
||||||
|
{
|
||||||
|
public static IHostBuilder UseContentRoot(this IHostBuilder hostBuilder, string contentRoot, bool createDirectory)
|
||||||
|
{
|
||||||
|
if (!Directory.Exists(contentRoot) && createDirectory)
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(contentRoot);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return hostBuilder.UseContentRoot(contentRoot);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +1,29 @@
|
|||||||
using Mediator;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||||
|
|
||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
|
|
||||||
|
public static class IServiceCollectionExtensions
|
||||||
{
|
{
|
||||||
public static class IServiceCollectionExtensions
|
public static IServiceCollection AddHandler<TRequestHandler>(this IServiceCollection serviceCollection)
|
||||||
{
|
{
|
||||||
public static IServiceCollection AddHandler<TRequestHandler>(this IServiceCollection serviceCollection)
|
serviceCollection.TryAdd(new ServiceDescriptor(typeof(TRequestHandler), typeof(TRequestHandler), ServiceLifetime.Transient));
|
||||||
{
|
return serviceCollection;
|
||||||
serviceCollection.TryAdd(new ServiceDescriptor(typeof(TRequestHandler), typeof(TRequestHandler), ServiceLifetime.Transient));
|
}
|
||||||
return serviceCollection;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static IServiceCollection AddFoundation(this IServiceCollection serviceCollection)
|
public static IServiceCollection AddFoundation(this IServiceCollection serviceCollection)
|
||||||
{
|
{
|
||||||
serviceCollection.AddSingleton<IServiceFactory>(provider => new ServiceFactory(provider.GetService, (instanceType, parameters) => ActivatorUtilities.CreateInstance(provider, instanceType, parameters!)));
|
serviceCollection.AddSingleton<IServiceFactory>(provider => new ServiceFactory(provider.GetService, (instanceType, parameters) => ActivatorUtilities.CreateInstance(provider, instanceType, parameters!)))
|
||||||
|
.AddSingleton<IInitialization, Initialization>(provider => new Initialization(() =>
|
||||||
|
{
|
||||||
|
return serviceCollection.Where(x => x.ServiceType.GetInterfaces()
|
||||||
|
.Contains(typeof(IInitializable)) || x.ServiceType == typeof(IInitializable))
|
||||||
|
.GroupBy(x => x.ServiceType)
|
||||||
|
.Select(x => x.First())
|
||||||
|
.SelectMany(x => provider.GetServices(x.ServiceType)
|
||||||
|
.Select(x => (IInitializable?)x)).ToList();
|
||||||
|
}));
|
||||||
|
|
||||||
return serviceCollection;
|
return serviceCollection;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,15 @@
|
|||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
{
|
|
||||||
public static class IServiceFactoryExtensions
|
|
||||||
{
|
|
||||||
public static T? Create<T>(this IServiceFactory serviceFactory, params object?[] parameters)
|
|
||||||
{
|
|
||||||
return serviceFactory.Create<T>(typeof(T), parameters);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static object? Create(this IServiceFactory serviceFactory, Type type)
|
public static class IServiceFactoryExtensions
|
||||||
{
|
{
|
||||||
ServiceFactoryDescriptor? descriptor = new(serviceFactory);
|
public static T? Create<T>(this IServiceFactory serviceFactory, params object?[] parameters)
|
||||||
return descriptor.Create(type);
|
{
|
||||||
}
|
return serviceFactory.Create<T>(typeof(T), parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static object? Create(this IServiceFactory serviceFactory, Type type)
|
||||||
|
{
|
||||||
|
ServiceFactoryDescriptor? descriptor = new(serviceFactory);
|
||||||
|
return descriptor.Create(type);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,26 +1,25 @@
|
|||||||
using Mediator;
|
using Mediator;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
|
|
||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
|
|
||||||
|
public class AppService : IHostedService
|
||||||
{
|
{
|
||||||
public class AppService : IHostedService
|
private readonly IMediator mediator;
|
||||||
|
|
||||||
|
public AppService(IMediator mediator)
|
||||||
{
|
{
|
||||||
private readonly IMediator mediator;
|
this.mediator = mediator;
|
||||||
|
}
|
||||||
|
|
||||||
public AppService(IMediator mediator)
|
public async Task StartAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
this.mediator = mediator;
|
await mediator.Send(new Initialize());
|
||||||
}
|
await mediator.Send(new Initialized());
|
||||||
|
}
|
||||||
|
|
||||||
public async Task StartAsync(CancellationToken cancellationToken)
|
public Task StopAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
await mediator.Send(new Initialization());
|
return Task.CompletedTask;
|
||||||
await mediator.Send(new Initialized());
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task StopAsync(CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
{
|
|
||||||
public interface ICache
|
public interface ICache
|
||||||
{
|
{
|
||||||
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace Toolkit.Foundation;
|
||||||
|
|
||||||
|
public interface IInitializable
|
||||||
|
{
|
||||||
|
Task InitializeAsync();
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace Toolkit.Foundation;
|
||||||
|
|
||||||
|
public interface IInitialization
|
||||||
|
{
|
||||||
|
Task InitializeAsync();
|
||||||
|
}
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
namespace Toolkit.Foundation
|
|
||||||
{
|
|
||||||
public interface IInitializer
|
|
||||||
{
|
|
||||||
Task InitializeAsync();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,22 @@
|
|||||||
using Mediator;
|
namespace Toolkit.Foundation;
|
||||||
|
|
||||||
namespace Toolkit.Foundation
|
public class Initialization : IInitialization
|
||||||
{
|
{
|
||||||
public record Initialization : IRequest;
|
private readonly Func<IEnumerable<IInitializable?>> factory;
|
||||||
|
|
||||||
|
public Initialization(Func<IEnumerable<IInitializable?>> factory)
|
||||||
|
{
|
||||||
|
this.factory = factory;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task InitializeAsync()
|
||||||
|
{
|
||||||
|
foreach (IInitializable? initializer in factory())
|
||||||
|
{
|
||||||
|
if (initializer is not null)
|
||||||
|
{
|
||||||
|
await initializer.InitializeAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
using Mediator;
|
|
||||||
|
|
||||||
namespace Toolkit.Foundation
|
|
||||||
{
|
|
||||||
public class InitializationHandler : IRequestHandler<Initialization>
|
|
||||||
{
|
|
||||||
private readonly IEnumerable<IInitializer?> initializers;
|
|
||||||
|
|
||||||
public InitializationHandler(IEnumerable<IInitializer?> initializers)
|
|
||||||
{
|
|
||||||
this.initializers = initializers;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async ValueTask<Unit> Handle(Initialization request, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
foreach (IInitializer? initializer in initializers)
|
|
||||||
{
|
|
||||||
if (initializer is not null)
|
|
||||||
{
|
|
||||||
await initializer.InitializeAsync();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return default;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
using Mediator;
|
||||||
|
|
||||||
|
namespace Toolkit.Foundation;
|
||||||
|
|
||||||
|
public record Initialize : IRequest;
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
using Mediator;
|
||||||
|
using System.Diagnostics;
|
||||||
|
|
||||||
|
namespace Toolkit.Foundation;
|
||||||
|
|
||||||
|
public class InitializeHandler : IRequestHandler<Initialize>
|
||||||
|
{
|
||||||
|
private readonly IEnumerable<IInitializable?> initializers;
|
||||||
|
|
||||||
|
public InitializeHandler(IEnumerable<IInitializable?> initializers)
|
||||||
|
{
|
||||||
|
this.initializers = initializers;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async ValueTask<Unit> Handle(Initialize request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
foreach (IInitializable? initializer in initializers)
|
||||||
|
{
|
||||||
|
if (initializer is not null)
|
||||||
|
{
|
||||||
|
Trace.WriteLine(initializer.GetType());
|
||||||
|
await initializer.InitializeAsync();
|
||||||
|
Trace.WriteLine("Done");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return default;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
using Mediator;
|
using Mediator;
|
||||||
|
|
||||||
namespace Toolkit.Foundation
|
namespace Toolkit.Foundation;
|
||||||
{
|
|
||||||
public record class Initialized : IRequest;
|
public record class Initialized : IRequest;
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user