Created
September 6, 2017 20:53
-
-
Save StephenCleary/abc02519d1946ce53574053e4e6eb5f7 to your computer and use it in GitHub Desktop.
AddJson and AddJsonObject extension methods for IConfigurationBuilder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public sealed class InMemoryFileProvider : IFileProvider | |
{ | |
private readonly string _json; | |
public InMemoryFileProvider(string json) | |
{ | |
_json = json; | |
} | |
public IFileInfo GetFileInfo(string subpath) => new FileInfo(_json); | |
IDirectoryContents IFileProvider.GetDirectoryContents(string subpath) => throw new NotImplementedException(); | |
IChangeToken IFileProvider.Watch(string filter) => throw new NotImplementedException(); | |
public sealed class FileInfo : IFileInfo | |
{ | |
private readonly string _json; | |
public FileInfo(string json) | |
{ | |
_json = json; | |
} | |
public Stream CreateReadStream() | |
{ | |
var result = new MemoryStream(); | |
using (var writer = new StreamWriter(result, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), 512, leaveOpen: true)) | |
writer.Write(_json); | |
result.Seek(0, SeekOrigin.Begin); | |
return result; | |
} | |
public bool Exists => true; | |
public bool IsDirectory => false; | |
public long Length => throw new NotImplementedException(); | |
public string PhysicalPath => throw new NotImplementedException(); | |
public string Name => throw new NotImplementedException(); | |
public DateTimeOffset LastModified => throw new NotImplementedException(); | |
} | |
} | |
public static class InMemoryExtensions | |
{ | |
public static IConfigurationBuilder AddJson(this IConfigurationBuilder builder, string json) => | |
builder.AddJsonFile(new InMemoryFileProvider(json), "path", optional: false, reloadOnChange: false); | |
public static IConfigurationBuilder AddJsonObject<T>(this IConfigurationBuilder builder, T instance) => | |
builder.AddJson(JsonConvert.SerializeObject(instance)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment