-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
FileConfigurationProvider.cs
163 lines (149 loc) · 5.82 KB
/
FileConfigurationProvider.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.ExceptionServices;
using System.Text;
using System.Threading;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Primitives;
namespace Microsoft.Extensions.Configuration
{
/// <summary>
/// Base class for file based <see cref="ConfigurationProvider"/>.
/// </summary>
public abstract class FileConfigurationProvider : ConfigurationProvider, IDisposable
{
private readonly IDisposable _changeTokenRegistration;
/// <summary>
/// Initializes a new instance with the specified source.
/// </summary>
/// <param name="source">The source settings.</param>
public FileConfigurationProvider(FileConfigurationSource source)
{
if (source == null)
{
throw new ArgumentNullException(nameof(source));
}
Source = source;
if (Source.ReloadOnChange && Source.FileProvider != null)
{
_changeTokenRegistration = ChangeToken.OnChange(
() => Source.FileProvider.Watch(Source.Path),
() =>
{
Thread.Sleep(Source.ReloadDelay);
Load(reload: true);
});
}
}
/// <summary>
/// The source settings for this provider.
/// </summary>
public FileConfigurationSource Source { get; }
/// <summary>
/// Generates a string representing this provider name and relevant details.
/// </summary>
/// <returns> The configuration name. </returns>
public override string ToString()
=> $"{GetType().Name} for '{Source.Path}' ({(Source.Optional ? "Optional" : "Required")})";
private void Load(bool reload)
{
IFileInfo file = Source.FileProvider?.GetFileInfo(Source.Path);
if (file == null || !file.Exists)
{
if (Source.Optional || reload) // Always optional on reload
{
Data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
else
{
var error = new StringBuilder($"The configuration file '{Source.Path}' was not found and is not optional.");
if (!string.IsNullOrEmpty(file?.PhysicalPath))
{
error.Append($" The physical path is '{file.PhysicalPath}'.");
}
HandleException(ExceptionDispatchInfo.Capture(new FileNotFoundException(error.ToString())));
}
}
else
{
static Stream OpenRead(IFileInfo fileInfo)
{
if (fileInfo.PhysicalPath != null)
{
// The default physical file info assumes asynchronous IO which results in unnecessary overhead
// especially since the configuration system is synchronous. This uses the same settings
// and disables async IO.
return new FileStream(
fileInfo.PhysicalPath,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite,
bufferSize: 1,
FileOptions.SequentialScan);
}
return fileInfo.CreateReadStream();
}
using Stream stream = OpenRead(file);
try
{
Load(stream);
}
catch (Exception e)
{
if (reload)
{
Data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
HandleException(ExceptionDispatchInfo.Capture(e));
}
}
// REVIEW: Should we raise this in the base as well / instead?
OnReload();
}
/// <summary>
/// Loads the contents of the file at <see cref="Path"/>.
/// </summary>
/// <exception cref="FileNotFoundException">If Optional is <c>false</c> on the source and a
/// file does not exist at specified Path.</exception>
public override void Load()
{
Load(reload: false);
}
/// <summary>
/// Loads this provider's data from a stream.
/// </summary>
/// <param name="stream">The stream to read.</param>
public abstract void Load(Stream stream);
private void HandleException(ExceptionDispatchInfo info)
{
bool ignoreException = false;
if (Source.OnLoadException != null)
{
var exceptionContext = new FileLoadExceptionContext
{
Provider = this,
Exception = info.SourceException
};
Source.OnLoadException.Invoke(exceptionContext);
ignoreException = exceptionContext.Ignore;
}
if (!ignoreException)
{
info.Throw();
}
}
/// <inheritdoc />
public void Dispose() => Dispose(true);
/// <summary>
/// Dispose the provider.
/// </summary>
/// <param name="disposing"><c>true</c> if invoked from <see cref="IDisposable.Dispose"/>.</param>
protected virtual void Dispose(bool disposing)
{
_changeTokenRegistration?.Dispose();
}
}
}