netcore-configuration

整个流程整理下。这种简单的Add可以运行。
1先创建ConfigurationSource继承FileConfigurtaionSource
    1)ConfigurationBuilder.Add(Source);
    2)Builder()->IConfigurationProvider Build(IConfigurationBuilder builder);产生Provider对象。加到ConfigurationRoot中。

2 创建ConfigurationProvide继承FileConfigurationProvide
3 具体使用builder.Configuration.Add<MyConfigurationSource>(config => config.Path="MyFile.json");

4 创建扩展方法*ConfigurationExtension。需要传递

public FileConfigurationProvider(FileConfigurationSource source)
        {
            ThrowHelper.ThrowIfNull(source);
 
            Source = source;
 
            if (Source.ReloadOnChange && Source.FileProvider != null)
            {
                _changeTokenRegistration = ChangeToken.OnChange(
                    () => Source.FileProvider.Watch(Source.Path!),
                    () =>
                    {
                        Thread.Sleep(Source.ReloadDelay);
                        Load(reload: true);
                    });
            }
        }



1关于:ConfigurationBuilder : IConfigurationBuilder
public IConfigurationBuilder Add(IConfigurationSource source)
{
            ThrowHelper.ThrowIfNull(source);
 
            Sources.Add(source);
            return this;
 }
2ConfigurationProvide
public class JsonConfigurationProvider : FileConfigurationProvider
{
        /// <summary>
        /// Initializes a new instance with the specified source.
        /// </summary>
        /// <param name="source">The source settings.</param>
        public JsonConfigurationProvider(JsonConfigurationSource source) : base(source) { }
 
        /// <summary>
        /// Loads the JSON data from a stream.
        /// </summary>
        /// <param name="stream">The stream to read.</param>
        public override void Load(Stream stream)
        {
            try
            {
                Data = JsonConfigurationFileParser.Parse(stream);
            }
            catch (JsonException e)
            {
                throw new FormatException(SR.Error_JSONParseError, e);
            }
        }
}

再看这个主要方法:路径必须存在才行。。。
public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, IFileProvider? provider, string path, bool optional, bool reloadOnChange)
{
            ThrowHelper.ThrowIfNull(builder);
 
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException(SR.Error_InvalidFilePath, nameof(path));
            }
         
            return builder.AddJsonFile(s =>
            {
                s.FileProvider = provider;
                s.Path = path;
                s.Optional = optional;
                s.ReloadOnChange = reloadOnChange;
                s.ResolveFileProvider();
            });
 }

 

posted @ 2023-05-27 09:56  vba是最好的语言  阅读(12)  评论(0编辑  收藏  举报