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:
None of the above answers worked for me. I am building a .net core 2.1 api.
I used
public class Startup
{
public static string ConnectionString {get; private set;}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
ConnectionString = Configuration.GetConnectionString("xxxxxx");
app.UseMvc();
}
Then whenever i need it i call string ConnString = Startup.ConnectionString;
Something like this should work:
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath).AddJsonFile("config.json");
Configuration = builder.Build();
var connStr = Configuration.Get("connString");
}
Docs: http://docs.asp.net/en/latest/fundamentals/configuration.html
Inside your startup, you should save the connection string to a static property on Startup
public class Startup
{
public static string ConnectionString { get; private set; }
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddUserSecrets();
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
ConnectionString = Configuration.Get<string>("Data:MongoDB:MongoServerSettings");
}
// ...
}
Then you should be able to access it from wherever:
public static string GetDefaultConnectionString()
{
return Startup.ConnectionString;
}
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.
1.ConnectionString in appsetting.json