7

I am in the process of learning ASP.NET vNext. I need to store two connection strings in the config.json file. How do I store those? Can I do this:

config.json

{
  "connectionStrings" : {
    "connection-1" : "server=...",
    "connection-2" : "server=..."
  }
}

I have not been able to find a schema for config.json. For that reason, I wasn't sure how to do it. I saw the use of IConfiguration here. Still, I wasn't sure how Configuration was available in the app.

3 Answers 3

6

This is the official Configuration repo and this is a great blog post explaining the configuration system.

Long story short:

  1. You need one or more Microsoft.Framework.ConfigurationModel.* NuGet packages in your application. The list of available packages is here.
  2. Add the configuration sources that you need
  3. Build the config file(s)
  4. Read the configuration sources
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for sharing. How would you use this model on a class library though? From what I can see, I would have to re-instantiate an IConfiguration object in every single instance of a class in my class library. This seems inefficient. Please correct me if I'm wrong.
You can inject IConfiguration or even hold a static reference to it somewhere...
Thank you for your patience. Do you know of an example of IConfiguration getting injected? I'm slowly learning this stuff :)
I wrote this article a while ago and except a few packages being renamed, it should be a good place to start with dependency injection in ASP.NET vNext blogs.msdn.com/b/webdev/archive/2014/06/17/…
2

Here is how you can do it:

 {   
      "Data": {
        "connection-1": {
          "ConnectionString": "Server=..."
        },
        "connection-2": {
          "ConnectionString": "Server=..."
        }   
}

}

Comments

0

This is how it's done these days...

{
  "ConnectionStrings": {
    "myDb1": "Server=myServer;Database=myDb1;Trusted_Connection=True;",
    "myDb2": "Server=myServer;Database=myDb2;Trusted_Connection=True;"
  }
}

From: Store and read connection string in appsettings.json

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.