在C#类库中使用IConfiguration [英] Using IConfiguration in C# Class Library
问题描述
我正在使用C#和Core .NET构建类库。我正在尝试使用 config.json
文件中的配置。该文件的内容如下:
I am building a class library using C# and Core .NET. I am trying to use configuration from a config.json
file. Here are the contents of that file:
config.json
{
"emailAddress":"someone@somewhere.com"
}
在尝试使用 config.json
进行配置时,我引用的是 Microsoft.Framework.ConfigurationModel.Json
在我的 project.json
文件中。在我的代码中,我有以下内容:
In an attempt to use config.json
for my configuration, I'm referencing Microsoft.Framework.ConfigurationModel.Json
in my project.json
file. In my code, I have the following:
MyClass.cs
using Microsoft.Framework.ConfigurationModel;
public class MyClass
{
public string GetEmailAddress()
{
// return ConfigurationManager.AppSettings["emailAddress"]; This is the approach I had been using since .NET 2.0
return ?; // What goes here?
}
}
自.NET 2.0起,我一直在使用 ConfigurationManager.AppSettings [ emailAddress]
。但是,我现在正在尝试通过 IConfiguration
来学习新方法。我的问题是,这是一个类库。因此,我不确定如何,何时何地加载配置文件。在传统的.NET中,我只需要为ASP.NET项目命名一个文件web.config,为其他项目命名一个app.config。现在,我不确定。我同时拥有一个ASP.NET MVC 6项目和一个XUnit项目。因此,我试图弄清楚如何在这两种情况下使用 config.json
。
Since .NET 2.0, I had been using ConfigurationManager.AppSettings["emailAddress"]
. However, I'm now trying to learn how to do it the new way via IConfiguration
. My problem is, this is a class library. For that reason, I'm not sure how, or where, or when, the configuration file gets loaded. In traditional .NET, I just needed to name a file web.config for ASP.NET projects and app.config for other projects. Now, I'm not sure. I have both an ASP.NET MVC 6 project and an XUnit project. So, I'm trying to figure out how to use config.json
in both of these scenarios.
谢谢您!
推荐答案
从未使用过,但快速搜索将其引导至此...
Never used it but a quick search lead me to this...
var configuration = new Configuration();
configuration.AddJsonFile("config.json");
var emailAddress = configuration.Get("emailAddress");
也许您可以尝试。
这篇关于在C#类库中使用IConfiguration的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!