[英]Is there a way to access appSettings.json globally?
I have a C# console app, and I'm defining an IConfiguration object as follows inside of Program.cs:我有一个 C# 控制台应用程序,我在 Program.cs 中定义了一个 IConfiguration object,如下所示:
var myConfig = new ConfigurationBuilder()
.AddJsonFile($"appsettings.{myEnvironment}.json", true, true)
.Build();
... and I can reference settings from within that same Program.cs file like this: ...我可以从同一个 Program.cs 文件中引用设置,如下所示:
var mySetting = myConfig.GetValue<string>("Section:SettingName");
However, I'm wondering what would be the way to access that same myConfig object from other files in my application?但是,我想知道从我的应用程序中的其他文件访问相同的 myConfig object 的方法是什么? For instance, myConfig contains a connection string, but I don't actually make use of the connection string until a few layers deeper (inside of myService > myRepository > myDbContext).例如,myConfig 包含一个连接字符串,但直到更深几层(在 myService > myRepository > myDbContext 内部)之前,我才真正使用连接字符串。 What is a best practice to read that connection string from inside of myRepository or myDbContext?从 myRepository 或 myDbContext 内部读取该连接字符串的最佳做法是什么? Obviously, I can pass the connection string as a parameter from Program.cs and myService, but that seems inefficient.显然,我可以将连接字符串作为 Program.cs 和 myService 的参数传递,但这似乎效率低下。
You can use the build-in DI (Dependency Injection), which also works for .NET C# Console Applications as already mentioned here您可以使用内置 DI(依赖注入),它也适用于 .NET C# 控制台应用程序,如此处所述
How to use Dependency Injection in.Net core Console Application 如何在.Net核心控制台应用程序中使用依赖注入
Pass IConfiguration
to your constructor.将IConfiguration
传递给您的构造函数。 You can use Bind
calls to create objects from it, or just read it like a dictionary.您可以使用Bind
调用从中创建对象,或者像字典一样读取它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.