2

I'm trying to get the connectionstring from the json-file to the DAL-class library with:

private static IConfigurationRoot config;
private static string connectionString;

public UserDAL()
{
    config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
    connectionString = config.GetConnectionString("DefaultString");
}

In the json-file:

{
  "ConnectionStrings": {
    "DefaultString": "theconnectionstring"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

The error happens when I try to open the connection, so con.Open();

4
  • 3
    It looks like your code accessing the config is correct. Why are you instantiating an IConfiguration in the constructor? You should be receiving it as a constructor parameter via DI. Commented Nov 19, 2019 at 13:06
  • what is DI? And I instantiate is in the constructor so when a UserDAL is created than it can use the config, else there's no use for accessig the json file...I think Commented Nov 19, 2019 at 13:10
  • DI = Dependency Injection. It's where you define your dependencies as constructor parameters, and the DI container builds your object. Basically @Fabjan answered this. Commented Nov 19, 2019 at 13:22
  • The code of accessing the configuration and getting the connectionString is ok.Where and what is your code to open the connection? Commented Nov 20, 2019 at 6:47

0

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.