Issues reading appsettings.json file C# .NET Core












0















I'm coming from regular .NET Web API and I have found the experience around configuration in .NET Core 2 absolutely maddening.



I have read the official documentation and a few tutorials such as this one, but they all see to error.



I have a Database helper class that is supposed to establish a MongoDB connection.



My configuration is rather simple



{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "mongodb://localhost:27017"
}
}



  • I started with the .NET Core official Angular (ngx) boilerplate template

  • I add the configuration as a service singleton in Startup.CS under the ConfigureServices section like so services.AddSingleton(Configuration);


  • I attempt to inject the configuration into my class like so



    public class DatabaseHelper
    {
    public static string connstring { get; private set; }
    public DatabaseHelper(IConfiguration Configuration)
    {
    connstring = Configuration["ConnectionStrings:DefaultConnectionString"];
    }


    public static IMongoDatabase QuizDB { get; } = GetDatabase("QuizEngine");
    public static IMongoCollection<Quiz> QuizCol { get; } = GetQuizCollection();


    public static MongoClient GetConnection() {

    return new MongoClient(connstring);
    }

    public static IMongoDatabase GetDatabase(string database) {

    MongoClient conn = DatabaseHelper.GetConnection();
    return conn.GetDatabase(database);
    }

    public static IMongoCollection<Quiz> GetQuizCollection() {
    return DatabaseHelper.QuizDB.GetCollection<Quiz>("Quizzes");
    }
    }



This compiles and builds fine with no Intellesense errors - But when I step through it in the debugger, the connstring is null. I have tried playing around with the configuration names etc, but I always seem to come up empty.



I have also tried the POCO way using the example code in the below answer, but I seem to run into static field initializer issues.



Getting value from appsettings.json in .net core



if it helps here is the the startup class part where it sets the public value of Configuration



    public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }









share|improve this question


















  • 5





    Is it a typo that your names don't match? DefaultConnection vs DefaultConnectionString

    – Chris
    Nov 25 '18 at 4:15






  • 2





    What Chris said. Plus, you shouldn't inject IConfiguration into your classes. Use the options pattern or directly inject the MongoClient(and register it via factory method, such as services.AddScoped<IMongoClient>(provider => new MongoClient(Configuration.GetConnectionString("DefaultConnection")));

    – Tseng
    Nov 25 '18 at 10:59











  • You can read more about the options pattern here: Options pattern in ASP.NET Core. P.S. it says Options pattern in ASP.NET Core, but it can also be applied to console applications

    – Tseng
    Nov 25 '18 at 11:35











  • @Chris you are correct I had a typo - However I tried changing it to something simpler (dburi) and it still showed as null.

    – Taylor Ackley
    Nov 25 '18 at 20:03






  • 1





    Ah, just noticed everything is static except the constructor. Are you calling these methods on an instance of your object that was instantiated by the DI container?

    – Chris
    Nov 25 '18 at 22:27
















0















I'm coming from regular .NET Web API and I have found the experience around configuration in .NET Core 2 absolutely maddening.



I have read the official documentation and a few tutorials such as this one, but they all see to error.



I have a Database helper class that is supposed to establish a MongoDB connection.



My configuration is rather simple



{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "mongodb://localhost:27017"
}
}



  • I started with the .NET Core official Angular (ngx) boilerplate template

  • I add the configuration as a service singleton in Startup.CS under the ConfigureServices section like so services.AddSingleton(Configuration);


  • I attempt to inject the configuration into my class like so



    public class DatabaseHelper
    {
    public static string connstring { get; private set; }
    public DatabaseHelper(IConfiguration Configuration)
    {
    connstring = Configuration["ConnectionStrings:DefaultConnectionString"];
    }


    public static IMongoDatabase QuizDB { get; } = GetDatabase("QuizEngine");
    public static IMongoCollection<Quiz> QuizCol { get; } = GetQuizCollection();


    public static MongoClient GetConnection() {

    return new MongoClient(connstring);
    }

    public static IMongoDatabase GetDatabase(string database) {

    MongoClient conn = DatabaseHelper.GetConnection();
    return conn.GetDatabase(database);
    }

    public static IMongoCollection<Quiz> GetQuizCollection() {
    return DatabaseHelper.QuizDB.GetCollection<Quiz>("Quizzes");
    }
    }



This compiles and builds fine with no Intellesense errors - But when I step through it in the debugger, the connstring is null. I have tried playing around with the configuration names etc, but I always seem to come up empty.



I have also tried the POCO way using the example code in the below answer, but I seem to run into static field initializer issues.



Getting value from appsettings.json in .net core



if it helps here is the the startup class part where it sets the public value of Configuration



    public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }









share|improve this question


















  • 5





    Is it a typo that your names don't match? DefaultConnection vs DefaultConnectionString

    – Chris
    Nov 25 '18 at 4:15






  • 2





    What Chris said. Plus, you shouldn't inject IConfiguration into your classes. Use the options pattern or directly inject the MongoClient(and register it via factory method, such as services.AddScoped<IMongoClient>(provider => new MongoClient(Configuration.GetConnectionString("DefaultConnection")));

    – Tseng
    Nov 25 '18 at 10:59











  • You can read more about the options pattern here: Options pattern in ASP.NET Core. P.S. it says Options pattern in ASP.NET Core, but it can also be applied to console applications

    – Tseng
    Nov 25 '18 at 11:35











  • @Chris you are correct I had a typo - However I tried changing it to something simpler (dburi) and it still showed as null.

    – Taylor Ackley
    Nov 25 '18 at 20:03






  • 1





    Ah, just noticed everything is static except the constructor. Are you calling these methods on an instance of your object that was instantiated by the DI container?

    – Chris
    Nov 25 '18 at 22:27














0












0








0








I'm coming from regular .NET Web API and I have found the experience around configuration in .NET Core 2 absolutely maddening.



I have read the official documentation and a few tutorials such as this one, but they all see to error.



I have a Database helper class that is supposed to establish a MongoDB connection.



My configuration is rather simple



{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "mongodb://localhost:27017"
}
}



  • I started with the .NET Core official Angular (ngx) boilerplate template

  • I add the configuration as a service singleton in Startup.CS under the ConfigureServices section like so services.AddSingleton(Configuration);


  • I attempt to inject the configuration into my class like so



    public class DatabaseHelper
    {
    public static string connstring { get; private set; }
    public DatabaseHelper(IConfiguration Configuration)
    {
    connstring = Configuration["ConnectionStrings:DefaultConnectionString"];
    }


    public static IMongoDatabase QuizDB { get; } = GetDatabase("QuizEngine");
    public static IMongoCollection<Quiz> QuizCol { get; } = GetQuizCollection();


    public static MongoClient GetConnection() {

    return new MongoClient(connstring);
    }

    public static IMongoDatabase GetDatabase(string database) {

    MongoClient conn = DatabaseHelper.GetConnection();
    return conn.GetDatabase(database);
    }

    public static IMongoCollection<Quiz> GetQuizCollection() {
    return DatabaseHelper.QuizDB.GetCollection<Quiz>("Quizzes");
    }
    }



This compiles and builds fine with no Intellesense errors - But when I step through it in the debugger, the connstring is null. I have tried playing around with the configuration names etc, but I always seem to come up empty.



I have also tried the POCO way using the example code in the below answer, but I seem to run into static field initializer issues.



Getting value from appsettings.json in .net core



if it helps here is the the startup class part where it sets the public value of Configuration



    public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }









share|improve this question














I'm coming from regular .NET Web API and I have found the experience around configuration in .NET Core 2 absolutely maddening.



I have read the official documentation and a few tutorials such as this one, but they all see to error.



I have a Database helper class that is supposed to establish a MongoDB connection.



My configuration is rather simple



{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "mongodb://localhost:27017"
}
}



  • I started with the .NET Core official Angular (ngx) boilerplate template

  • I add the configuration as a service singleton in Startup.CS under the ConfigureServices section like so services.AddSingleton(Configuration);


  • I attempt to inject the configuration into my class like so



    public class DatabaseHelper
    {
    public static string connstring { get; private set; }
    public DatabaseHelper(IConfiguration Configuration)
    {
    connstring = Configuration["ConnectionStrings:DefaultConnectionString"];
    }


    public static IMongoDatabase QuizDB { get; } = GetDatabase("QuizEngine");
    public static IMongoCollection<Quiz> QuizCol { get; } = GetQuizCollection();


    public static MongoClient GetConnection() {

    return new MongoClient(connstring);
    }

    public static IMongoDatabase GetDatabase(string database) {

    MongoClient conn = DatabaseHelper.GetConnection();
    return conn.GetDatabase(database);
    }

    public static IMongoCollection<Quiz> GetQuizCollection() {
    return DatabaseHelper.QuizDB.GetCollection<Quiz>("Quizzes");
    }
    }



This compiles and builds fine with no Intellesense errors - But when I step through it in the debugger, the connstring is null. I have tried playing around with the configuration names etc, but I always seem to come up empty.



I have also tried the POCO way using the example code in the below answer, but I seem to run into static field initializer issues.



Getting value from appsettings.json in .net core



if it helps here is the the startup class part where it sets the public value of Configuration



    public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }






c# asp.net-core






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 25 '18 at 0:50









Taylor AckleyTaylor Ackley

800824




800824








  • 5





    Is it a typo that your names don't match? DefaultConnection vs DefaultConnectionString

    – Chris
    Nov 25 '18 at 4:15






  • 2





    What Chris said. Plus, you shouldn't inject IConfiguration into your classes. Use the options pattern or directly inject the MongoClient(and register it via factory method, such as services.AddScoped<IMongoClient>(provider => new MongoClient(Configuration.GetConnectionString("DefaultConnection")));

    – Tseng
    Nov 25 '18 at 10:59











  • You can read more about the options pattern here: Options pattern in ASP.NET Core. P.S. it says Options pattern in ASP.NET Core, but it can also be applied to console applications

    – Tseng
    Nov 25 '18 at 11:35











  • @Chris you are correct I had a typo - However I tried changing it to something simpler (dburi) and it still showed as null.

    – Taylor Ackley
    Nov 25 '18 at 20:03






  • 1





    Ah, just noticed everything is static except the constructor. Are you calling these methods on an instance of your object that was instantiated by the DI container?

    – Chris
    Nov 25 '18 at 22:27














  • 5





    Is it a typo that your names don't match? DefaultConnection vs DefaultConnectionString

    – Chris
    Nov 25 '18 at 4:15






  • 2





    What Chris said. Plus, you shouldn't inject IConfiguration into your classes. Use the options pattern or directly inject the MongoClient(and register it via factory method, such as services.AddScoped<IMongoClient>(provider => new MongoClient(Configuration.GetConnectionString("DefaultConnection")));

    – Tseng
    Nov 25 '18 at 10:59











  • You can read more about the options pattern here: Options pattern in ASP.NET Core. P.S. it says Options pattern in ASP.NET Core, but it can also be applied to console applications

    – Tseng
    Nov 25 '18 at 11:35











  • @Chris you are correct I had a typo - However I tried changing it to something simpler (dburi) and it still showed as null.

    – Taylor Ackley
    Nov 25 '18 at 20:03






  • 1





    Ah, just noticed everything is static except the constructor. Are you calling these methods on an instance of your object that was instantiated by the DI container?

    – Chris
    Nov 25 '18 at 22:27








5




5





Is it a typo that your names don't match? DefaultConnection vs DefaultConnectionString

– Chris
Nov 25 '18 at 4:15





Is it a typo that your names don't match? DefaultConnection vs DefaultConnectionString

– Chris
Nov 25 '18 at 4:15




2




2





What Chris said. Plus, you shouldn't inject IConfiguration into your classes. Use the options pattern or directly inject the MongoClient(and register it via factory method, such as services.AddScoped<IMongoClient>(provider => new MongoClient(Configuration.GetConnectionString("DefaultConnection")));

– Tseng
Nov 25 '18 at 10:59





What Chris said. Plus, you shouldn't inject IConfiguration into your classes. Use the options pattern or directly inject the MongoClient(and register it via factory method, such as services.AddScoped<IMongoClient>(provider => new MongoClient(Configuration.GetConnectionString("DefaultConnection")));

– Tseng
Nov 25 '18 at 10:59













You can read more about the options pattern here: Options pattern in ASP.NET Core. P.S. it says Options pattern in ASP.NET Core, but it can also be applied to console applications

– Tseng
Nov 25 '18 at 11:35





You can read more about the options pattern here: Options pattern in ASP.NET Core. P.S. it says Options pattern in ASP.NET Core, but it can also be applied to console applications

– Tseng
Nov 25 '18 at 11:35













@Chris you are correct I had a typo - However I tried changing it to something simpler (dburi) and it still showed as null.

– Taylor Ackley
Nov 25 '18 at 20:03





@Chris you are correct I had a typo - However I tried changing it to something simpler (dburi) and it still showed as null.

– Taylor Ackley
Nov 25 '18 at 20:03




1




1





Ah, just noticed everything is static except the constructor. Are you calling these methods on an instance of your object that was instantiated by the DI container?

– Chris
Nov 25 '18 at 22:27





Ah, just noticed everything is static except the constructor. Are you calling these methods on an instance of your object that was instantiated by the DI container?

– Chris
Nov 25 '18 at 22:27












3 Answers
3






active

oldest

votes


















2














You don't need to add the configuration as a service singleton in Startup.CS under the ConfigureServices section like services.AddSingleton(Configuration);



If you separate your solution into multiple projects with use of class libraries, Microsoft.Extensions.Options.ConfigurationExtensions package comes in handy for reading the values from appsettings files and injecting them into your configuration classes within projects.



It has 2 extensions you can use:



public static T Get<T>(this IConfiguration configuration);
public static IServiceCollection Configure<TOptions>(this IServiceCollection services,
IConfiguration config) where TOptions : class;


your configuration file appsetting.json



{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"MongoDBConnection": "mongodb://localhost:27017"
}
}


add code for ConfigureServices method in startup.cs file



  services.Configure<MongoDBconfig>(Configuration.GetSection("ConnectionStrings"));
services.AddSingleton<DatabaseHelper>();


your DBhelper.cs



    public class MongoDBconfig
{
public string MongoDBConnection { get; set; }
}

public class DatabaseHelper
{
public static string connstring { get; private set; }
public DatabaseHelper(IOptions<MongoDBconfig> Configuration)
{
connstring = Configuration.Value.MongoDBConnection;
}


public static IMongoDatabase QuizDB { get; } = GetDatabase("QuizEngine");
public static IMongoCollection<Quiz> QuizCol { get; } = GetQuizCollection();


public static MongoClient GetConnection()
{

return new MongoClient(connstring);
}

public static IMongoDatabase GetDatabase(string database)
{

MongoClient conn = DatabaseHelper.GetConnection();
return conn.GetDatabase(database);
}

public static IMongoCollection<Quiz> GetQuizCollection()
{
return DatabaseHelper.QuizDB.GetCollection<Quiz>("Quizzes");
}
}





share|improve this answer
























  • Thanks - I'll check this out.

    – Taylor Ackley
    Nov 26 '18 at 17:40



















0














Try the following way using this extension method GetConnectionString



public DatabaseHelper(IConfiguration Configuration)
{
connstring = Configuration.GetConnectionString("DefaultConnection");
}





share|improve this answer


























  • Came back as null :(

    – Taylor Ackley
    Nov 25 '18 at 20:14



















0














Try this



public DatabaseHelper(IConfiguration Configuration)
{
string test = Configuration.GetSection("ConnectionStrings")["DefaultConnection"];
Console.WriteLine(test);

}


Check if this able to extract the value in your appsettings.json






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53463746%2fissues-reading-appsettings-json-file-c-sharp-net-core%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    You don't need to add the configuration as a service singleton in Startup.CS under the ConfigureServices section like services.AddSingleton(Configuration);



    If you separate your solution into multiple projects with use of class libraries, Microsoft.Extensions.Options.ConfigurationExtensions package comes in handy for reading the values from appsettings files and injecting them into your configuration classes within projects.



    It has 2 extensions you can use:



    public static T Get<T>(this IConfiguration configuration);
    public static IServiceCollection Configure<TOptions>(this IServiceCollection services,
    IConfiguration config) where TOptions : class;


    your configuration file appsetting.json



    {
    "Logging": {
    "LogLevel": {
    "Default": "Warning"
    }
    },
    "AllowedHosts": "*",
    "ConnectionStrings": {
    "MongoDBConnection": "mongodb://localhost:27017"
    }
    }


    add code for ConfigureServices method in startup.cs file



      services.Configure<MongoDBconfig>(Configuration.GetSection("ConnectionStrings"));
    services.AddSingleton<DatabaseHelper>();


    your DBhelper.cs



        public class MongoDBconfig
    {
    public string MongoDBConnection { get; set; }
    }

    public class DatabaseHelper
    {
    public static string connstring { get; private set; }
    public DatabaseHelper(IOptions<MongoDBconfig> Configuration)
    {
    connstring = Configuration.Value.MongoDBConnection;
    }


    public static IMongoDatabase QuizDB { get; } = GetDatabase("QuizEngine");
    public static IMongoCollection<Quiz> QuizCol { get; } = GetQuizCollection();


    public static MongoClient GetConnection()
    {

    return new MongoClient(connstring);
    }

    public static IMongoDatabase GetDatabase(string database)
    {

    MongoClient conn = DatabaseHelper.GetConnection();
    return conn.GetDatabase(database);
    }

    public static IMongoCollection<Quiz> GetQuizCollection()
    {
    return DatabaseHelper.QuizDB.GetCollection<Quiz>("Quizzes");
    }
    }





    share|improve this answer
























    • Thanks - I'll check this out.

      – Taylor Ackley
      Nov 26 '18 at 17:40
















    2














    You don't need to add the configuration as a service singleton in Startup.CS under the ConfigureServices section like services.AddSingleton(Configuration);



    If you separate your solution into multiple projects with use of class libraries, Microsoft.Extensions.Options.ConfigurationExtensions package comes in handy for reading the values from appsettings files and injecting them into your configuration classes within projects.



    It has 2 extensions you can use:



    public static T Get<T>(this IConfiguration configuration);
    public static IServiceCollection Configure<TOptions>(this IServiceCollection services,
    IConfiguration config) where TOptions : class;


    your configuration file appsetting.json



    {
    "Logging": {
    "LogLevel": {
    "Default": "Warning"
    }
    },
    "AllowedHosts": "*",
    "ConnectionStrings": {
    "MongoDBConnection": "mongodb://localhost:27017"
    }
    }


    add code for ConfigureServices method in startup.cs file



      services.Configure<MongoDBconfig>(Configuration.GetSection("ConnectionStrings"));
    services.AddSingleton<DatabaseHelper>();


    your DBhelper.cs



        public class MongoDBconfig
    {
    public string MongoDBConnection { get; set; }
    }

    public class DatabaseHelper
    {
    public static string connstring { get; private set; }
    public DatabaseHelper(IOptions<MongoDBconfig> Configuration)
    {
    connstring = Configuration.Value.MongoDBConnection;
    }


    public static IMongoDatabase QuizDB { get; } = GetDatabase("QuizEngine");
    public static IMongoCollection<Quiz> QuizCol { get; } = GetQuizCollection();


    public static MongoClient GetConnection()
    {

    return new MongoClient(connstring);
    }

    public static IMongoDatabase GetDatabase(string database)
    {

    MongoClient conn = DatabaseHelper.GetConnection();
    return conn.GetDatabase(database);
    }

    public static IMongoCollection<Quiz> GetQuizCollection()
    {
    return DatabaseHelper.QuizDB.GetCollection<Quiz>("Quizzes");
    }
    }





    share|improve this answer
























    • Thanks - I'll check this out.

      – Taylor Ackley
      Nov 26 '18 at 17:40














    2












    2








    2







    You don't need to add the configuration as a service singleton in Startup.CS under the ConfigureServices section like services.AddSingleton(Configuration);



    If you separate your solution into multiple projects with use of class libraries, Microsoft.Extensions.Options.ConfigurationExtensions package comes in handy for reading the values from appsettings files and injecting them into your configuration classes within projects.



    It has 2 extensions you can use:



    public static T Get<T>(this IConfiguration configuration);
    public static IServiceCollection Configure<TOptions>(this IServiceCollection services,
    IConfiguration config) where TOptions : class;


    your configuration file appsetting.json



    {
    "Logging": {
    "LogLevel": {
    "Default": "Warning"
    }
    },
    "AllowedHosts": "*",
    "ConnectionStrings": {
    "MongoDBConnection": "mongodb://localhost:27017"
    }
    }


    add code for ConfigureServices method in startup.cs file



      services.Configure<MongoDBconfig>(Configuration.GetSection("ConnectionStrings"));
    services.AddSingleton<DatabaseHelper>();


    your DBhelper.cs



        public class MongoDBconfig
    {
    public string MongoDBConnection { get; set; }
    }

    public class DatabaseHelper
    {
    public static string connstring { get; private set; }
    public DatabaseHelper(IOptions<MongoDBconfig> Configuration)
    {
    connstring = Configuration.Value.MongoDBConnection;
    }


    public static IMongoDatabase QuizDB { get; } = GetDatabase("QuizEngine");
    public static IMongoCollection<Quiz> QuizCol { get; } = GetQuizCollection();


    public static MongoClient GetConnection()
    {

    return new MongoClient(connstring);
    }

    public static IMongoDatabase GetDatabase(string database)
    {

    MongoClient conn = DatabaseHelper.GetConnection();
    return conn.GetDatabase(database);
    }

    public static IMongoCollection<Quiz> GetQuizCollection()
    {
    return DatabaseHelper.QuizDB.GetCollection<Quiz>("Quizzes");
    }
    }





    share|improve this answer













    You don't need to add the configuration as a service singleton in Startup.CS under the ConfigureServices section like services.AddSingleton(Configuration);



    If you separate your solution into multiple projects with use of class libraries, Microsoft.Extensions.Options.ConfigurationExtensions package comes in handy for reading the values from appsettings files and injecting them into your configuration classes within projects.



    It has 2 extensions you can use:



    public static T Get<T>(this IConfiguration configuration);
    public static IServiceCollection Configure<TOptions>(this IServiceCollection services,
    IConfiguration config) where TOptions : class;


    your configuration file appsetting.json



    {
    "Logging": {
    "LogLevel": {
    "Default": "Warning"
    }
    },
    "AllowedHosts": "*",
    "ConnectionStrings": {
    "MongoDBConnection": "mongodb://localhost:27017"
    }
    }


    add code for ConfigureServices method in startup.cs file



      services.Configure<MongoDBconfig>(Configuration.GetSection("ConnectionStrings"));
    services.AddSingleton<DatabaseHelper>();


    your DBhelper.cs



        public class MongoDBconfig
    {
    public string MongoDBConnection { get; set; }
    }

    public class DatabaseHelper
    {
    public static string connstring { get; private set; }
    public DatabaseHelper(IOptions<MongoDBconfig> Configuration)
    {
    connstring = Configuration.Value.MongoDBConnection;
    }


    public static IMongoDatabase QuizDB { get; } = GetDatabase("QuizEngine");
    public static IMongoCollection<Quiz> QuizCol { get; } = GetQuizCollection();


    public static MongoClient GetConnection()
    {

    return new MongoClient(connstring);
    }

    public static IMongoDatabase GetDatabase(string database)
    {

    MongoClient conn = DatabaseHelper.GetConnection();
    return conn.GetDatabase(database);
    }

    public static IMongoCollection<Quiz> GetQuizCollection()
    {
    return DatabaseHelper.QuizDB.GetCollection<Quiz>("Quizzes");
    }
    }






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 26 '18 at 8:23









    KhushaliKhushali

    905




    905













    • Thanks - I'll check this out.

      – Taylor Ackley
      Nov 26 '18 at 17:40



















    • Thanks - I'll check this out.

      – Taylor Ackley
      Nov 26 '18 at 17:40

















    Thanks - I'll check this out.

    – Taylor Ackley
    Nov 26 '18 at 17:40





    Thanks - I'll check this out.

    – Taylor Ackley
    Nov 26 '18 at 17:40













    0














    Try the following way using this extension method GetConnectionString



    public DatabaseHelper(IConfiguration Configuration)
    {
    connstring = Configuration.GetConnectionString("DefaultConnection");
    }





    share|improve this answer


























    • Came back as null :(

      – Taylor Ackley
      Nov 25 '18 at 20:14
















    0














    Try the following way using this extension method GetConnectionString



    public DatabaseHelper(IConfiguration Configuration)
    {
    connstring = Configuration.GetConnectionString("DefaultConnection");
    }





    share|improve this answer


























    • Came back as null :(

      – Taylor Ackley
      Nov 25 '18 at 20:14














    0












    0








    0







    Try the following way using this extension method GetConnectionString



    public DatabaseHelper(IConfiguration Configuration)
    {
    connstring = Configuration.GetConnectionString("DefaultConnection");
    }





    share|improve this answer















    Try the following way using this extension method GetConnectionString



    public DatabaseHelper(IConfiguration Configuration)
    {
    connstring = Configuration.GetConnectionString("DefaultConnection");
    }






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 25 '18 at 4:47

























    answered Nov 25 '18 at 3:53









    GonzaHGonzaH

    1417




    1417













    • Came back as null :(

      – Taylor Ackley
      Nov 25 '18 at 20:14



















    • Came back as null :(

      – Taylor Ackley
      Nov 25 '18 at 20:14

















    Came back as null :(

    – Taylor Ackley
    Nov 25 '18 at 20:14





    Came back as null :(

    – Taylor Ackley
    Nov 25 '18 at 20:14











    0














    Try this



    public DatabaseHelper(IConfiguration Configuration)
    {
    string test = Configuration.GetSection("ConnectionStrings")["DefaultConnection"];
    Console.WriteLine(test);

    }


    Check if this able to extract the value in your appsettings.json






    share|improve this answer




























      0














      Try this



      public DatabaseHelper(IConfiguration Configuration)
      {
      string test = Configuration.GetSection("ConnectionStrings")["DefaultConnection"];
      Console.WriteLine(test);

      }


      Check if this able to extract the value in your appsettings.json






      share|improve this answer


























        0












        0








        0







        Try this



        public DatabaseHelper(IConfiguration Configuration)
        {
        string test = Configuration.GetSection("ConnectionStrings")["DefaultConnection"];
        Console.WriteLine(test);

        }


        Check if this able to extract the value in your appsettings.json






        share|improve this answer













        Try this



        public DatabaseHelper(IConfiguration Configuration)
        {
        string test = Configuration.GetSection("ConnectionStrings")["DefaultConnection"];
        Console.WriteLine(test);

        }


        Check if this able to extract the value in your appsettings.json







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 26 '18 at 13:18









        klitzklitz

        285




        285






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53463746%2fissues-reading-appsettings-json-file-c-sharp-net-core%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Lallio

            Unable to find Lightning Node

            Futebolista