read connectionstring outside startup from appsetting.json in vNext

后端 未结 5 893
终归单人心
终归单人心 2020-12-14 02:52

I have a project class (Nuget Package). I need to read in a static class without constructor my connections string to MongoDB.

Static Class Method:

5条回答
  •  时光取名叫无心
    2020-12-14 03:17

    How can I obtain the value outside the Startup.cs without using DI? It is possible?

    Yes, you can using Configuration without DI and throughout your application. But recommended way using Configuration API only in Startup and then Using Options:

    create well-factored settings objects that correspond to certain features within your application, thus following the Interface Segregation Principle (ISP) (classes depend only on the configuration settings they use)

    Example using Configuration API

    appsettings.json:

    {
      "Name": "Stas",
      "Surname": "Boyarincev"
    }
    

    Using Configuration:

    var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
    
    var Configuration = builder.Build();
    
    var name = Configuration.GetSection("name");
    var surname = Configuration.GetSection("surname");
    

    tutorial on docs.asp.net - but it a bit outdated.

提交回复
热议问题