【问题标题】:.NET 6.0 - read appsettings.json values from class library.NET 6.0 - 从类库中读取 appsettings.json 值
【发布时间】:2021-12-15 08:07:27
【问题描述】:

.NET 6.0 - 从类库中获取 appsettings.json 值。我有一个 .NET 6.0 web api 项目,另一个是类库。

我想将一些设置读入类库。

我们在 web api 项目中有 appsettings.json。 如何在类库中读取这些值?

能否请您提供正确的代码 sn-ps

我是 .net core 6 的新手,也是依赖注入等等

【问题讨论】:

  • 我投票结束这个问题,因为你已经多次问过这个问题(例如here)。

标签: .net-core .net-6.0


【解决方案1】:

在您想要读取值的类库中,您应该能够使用ConfigurationBuilder 访问 json 文件。首先,定义appsettings.json的位置:

string filePath = @"C:\MyDir\MySubDirWhereAppSettingsIsLocated\appSettings.json"; //this is where appSettings.json is located

然后在尝试访问文件时使用filePath

IConfiguration myConfig = new ConfigurationBuilder()
   .SetBasePath(Path.GetDirectoryName(filePath))
   .AddJsonFile("appSettings.json")
   .Build();

然后,您可以像这样访问appsettings.json 中的各个值:

string myValue = myConfig.GetValue<string>("nameOfMyValue");

注意你需要导入 NuGet 包Microsoft.Extensions.Configuration

【讨论】:

  • 我认为,一般来说,您应该避免读取类库项目中的设置,而是公开一些 API 以将解析后的设置传递给库。
  • 你还需要包Microsoft.Extensions.Configuration.Json
  • @Maze90 我目前在我的一个项目中使用上述解决方案,而不参考Microsoft.Extensions.Configuration.Json - 仅Microsoft.Extensions.Configuration
  • @GuruStron 这听起来不错。如果你有一个例子的链接,我很想看到它。
  • @mnc 示例中没有太多可展示的内容。这个想法听起来很简单。见ExampleServicehere(可能没有IOptions)。基本上,服务可以位于库中,托管项目负责实例化(通过 DI 或手动)并提供设置(再次 - 通过 DI 或手动)。
猜你喜欢
  • 2018-11-06
  • 1970-01-01
  • 2018-05-05
  • 2023-01-29
  • 2020-06-11
  • 1970-01-01
  • 1970-01-01
  • 2018-04-07
相关资源
最近更新 更多