Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AddJson and AddJsonObject extension methods for IConfigurationBuilder
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
You can’t perform that action at this time.