Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading startup configuration from JSON located in memory

Tags:

I am researching about how to load the startup config in .NET Core. I notice there are different ways to do that, I have seen XML, JSON, init file, and from a Dictionary located in memory (I will go back to this later). I'm using something like the code below:

new ConfigurationBuilder().AddJsonFile("file.json").Build(); 

All of that is OK, but, isn't there any way to load that configuration from a JSON string? I mean, I don't want to store the json in a temporal file because is a real-time built file and It makes no sense.

About the dictionary located in memory. Its easy to build it manually, but, What about for complex and too hierarchical JSON structures? As far as I know, the dictionary is

dictionary < string, string >

whose key is the parents of the tree concatenated by ":" managing at the same time the repeated nodes, enumerating them, etc. A pain build this algorithm from scratch.

like image 495
mra Avatar asked Jun 28 '17 16:06

mra


2 Answers

Use NuGet package Microsoft.Extensions.Configuration.Json >= 3.0.0

var json = "{ \"option1\": 1, \"option2\": \"abc\", }"; var configuration = new ConfigurationBuilder().AddJsonStream(new MemoryStream(Encoding.ASCII.GetBytes(json))).Build(); 
like image 58
FatTiger Avatar answered Oct 12 '22 13:10

FatTiger


I liked Adam's answer a lot, but the interface implementations he linked to were a bit monolithic. Here is a smaller one:

public class InMemoryFileProvider : IFileProvider {     private class InMemoryFile : IFileInfo     {         private readonly byte[] _data;         public InMemoryFile(string json) => _data = Encoding.UTF8.GetBytes(json);         public Stream CreateReadStream() => new MemoryStream(_data);         public bool Exists { get; } = true;         public long Length => _data.Length;         public string PhysicalPath { get; } = string.Empty;         public string Name { get; } = string.Empty;         public DateTimeOffset LastModified { get; } = DateTimeOffset.UtcNow;         public bool IsDirectory { get; } = false;     }      private readonly IFileInfo _fileInfo;     public InMemoryFileProvider(string json) => _fileInfo = new InMemoryFile(json);     public IFileInfo GetFileInfo(string _) => _fileInfo;     public IDirectoryContents GetDirectoryContents(string _) => null;     public IChangeToken Watch(string _) => NullChangeToken.Singleton; } 

Then, as per Adam's answer, you can use:

var memoryFileProvider = new InMemoryFileProvider(jsonString); var configuration = new ConfigurationBuilder()     .AddJsonFile(memoryFileProvider, "appsettings.json", false, false)     .Build(); 
like image 33
Rob Lyndon Avatar answered Oct 12 '22 12:10

Rob Lyndon