我正在使用C#和Core .NET构建一个类库。我正在尝试使用config.json
文件中的配置。以下是该文件的内容:
config.json
{
"emailAddress":"someone@somewhere.com"
}
尝试使用config.json
进行配置时,我在Microsoft.Framework.ConfigurationModel.Json
文件中引用了project.json
。在我的代码中,我有以下内容:
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
。
谢谢!
答案 0 :(得分:49)
IMO类库应该与应用程序设置数据无关。通常,图书馆消费者是关注这些细节的人。是的,这并非总是如此(例如,如果您有一个进行RSA加密/解密的类,您可能需要一些私有配置来允许私钥生成/存储),但在大多数情况下,这是真的。 / p>
因此,通常,尝试将应用程序设置保留在类库之外,并让使用者提供此类数据。在您的评论中,您提到了数据库的连接字符串。这是保存在类库之外的数据的完美示例。该库不应该关心它要读取的数据库,只需要从中读取它。下面的例子(如果因为我在内存中动态写这个错误,我道歉):
<强>库强>
使用连接字符串的库类
public class LibraryClassThatNeedsConnectionString
{
private string connectionString;
public LibraryClassThatNeedsConnectionString(string connectionString)
{
this.connectionString = connectionString;
}
public string ReadTheDatabase(int somePrimaryKeyIdToRead)
{
var result = string.Empty;
// Read your database and set result
return result;
}
}
<强>应用强>
appsettings.json
{
"DatabaseSettings": {
"ConnectionString": "MySuperCoolConnectionStringWouldGoHere"
}
}
DatabaseSettings.cs
public class DatabaseSettings
{
public string ConnectionString { get; set; }
}
Startup.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
Configuration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables()
.Build();
}
public IConfigurationRoot Configuration { get; }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Setup logging
// Configure app
}
public void ConfigureServices(IServiceCollection services)
{
// Configure services
services.Configure<DatabaseSettings>(Configuration.GetSection("DatabaseSettings"));
services.AddOptions();
// Register our class that reads the DB into the DI framework
services.AddTransient<IInterfaceForClass, ClassThatNeedsToReadDatabaseUsingLibrary>();
}
}
使用库类读取数据库的类
public interface IInterfaceForClass
{
string ReadDatabaseUsingClassLibrary(int somePrimaryKeyIdToRead);
}
public class ClassThatNeedsToReadDatabaseUsingLibrary : IInterfaceForClass
{
private DatabaseSettings dbSettings;
private LibraryClassThatNeedsConnectionString libraryClassThatNeedsConnectionString;
public ClassThatNeedsToReadDatabaseUsingLibrary(IOptions<DatabaseSettings> dbOptions)
{
this.dbSettings = dbOptions.Value;
this.libraryClassThatNeedsConnectionString = new LibraryClassThatNeedsConnectionString(this.dbSettings.ConnectionString);
}
public string ReadDatabaseUsingClassLibrary(int somePrimaryKeyIdToRead)
{
return this.libraryClassThatNeedsConnectionString.ReadTheDatabase(somePrimaryKeyIdToRead);
}
}
一些控制器类,用于处理从DB中读取的UI内容
public class SomeController : Controller
{
private readonly classThatReadsFromDb;
public SomeController(IInterfaceForClass classThatReadsFromDb)
{
this.classThatReadsFromDb = classThatReadsFromDb;
}
// Controller methods
}
<强> TL; DR 强>
尽量避免在类库中使用应用程序设置。相反,让您的类库与这些设置无关,并让消费者传递这些设置。
修改强>
我在依赖注入中添加了一个控制器类来演示使用依赖注入来构建从DB读取的类。这使得DI系统可以解决必要的依赖关系(例如数据库选项)。
这是做到这一点的一种方式(也是最好的方式)。另一种方法是将IOptions注入控制器并手动新建从DB读取并传递选项的类(不是最佳实践,DI是更好的方法)
答案 1 :(得分:8)
从未使用它,但快速搜索引导我...
var configuration = new Configuration();
configuration.AddJsonFile(“config.json”);
var emailAddress = configuration.Get("emailAddress");
也许你可以试试。
答案 2 :(得分:0)
首先在.csproj
文件中添加target that hocks in the build process,如果以下内容不符合您的需求,请参阅更多选项的链接,例如发布
<Target Name="AddConfig" AfterTargets="AfterBuild">
<Copy SourceFiles="config.json" DestinationFolder="$(OutDir)" />
</Target>
你可以像下面那样使用它
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Extensions.Configuration;
using System;
public class MyClass {
public string GetEmailAddress() {
//For example purpose only, try to move this to a right place like configuration manager class
string basePath= System.AppContext.BaseDirectory;
IConfigurationRoot configuration= new ConfigurationBuilder()
.SetBasePath(basePath)
.AddJsonFile("config.json")
.Build();
return configuration.Get("emailAddress");
}
}
答案 3 :(得分:0)
这应该有效。需要安装软件包Microsoft.Extensions.Configuration.Json
public static class Config
{
private static IConfiguration configuration;
static Config()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
configuration = builder.Build();
}
public static string Get(string name)
{
string appSettings = configuration[name];
return appSettings;
}
}
答案 4 :(得分:0)
您还可以通过右键单击 .csproject -> properties-> settings-> 在右侧窗口中添加新属性来设置类库的属性。 确保在访问修饰符下拉列表中将访问修饰符选择为公共。
现在,将类库项目引用添加到您的 .net 核心项目。
<块引用>如下所述创建 appSettings.cs 类
public class AppSettings
{
public string MyConnectionString { get; set; }
}
<块引用>
设置键值 appSettings.json
"AppSettings": {
"MyConnectionString": "yourconnectionstring",
},
<块引用>现在,我们只需要从 appSettings.json 获取连接字符串和 在 Startup.cs 中将属性设置到类库中,如下所示。
// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// inject App setting
var appSettingSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingSection);
var appsetting = appSettingSection.Get<AppSettings>();
// set connection string in .csproject properties.
classLibraryProject.Properties.Settings.Default.Properties["MyConnectionString"].DefaultValue = appsetting.MyconnectionString;
}
注意:
我希望这会有所帮助。
答案 5 :(得分:0)
如果有人想看到它,例如 Asp.net Core .Net 5.0。我已经完成了上述答案并为我的应用程序稍微调整了我的代码。
如果您想了解如何在控制台应用程序中使用它,请访问我对此 link 的回答,我还添加了带有电子邮件地址的示例。
我的 AppSettings.Json 是:
{
"AppSettings": {
"FTPLocation": "\\\\hostname\\\\c$\\\\FTPMainFolder\\\\ftpFolder\\\\Test\\",
"FTPUri": "ftp://hostname.domainname.com/foldername/",
"CSVFileName": "Test Load Planning.csv"
},
"ConnectionStrings":
{
"AppDbConnString": "Server=sqlserverhostname.domainname.com;Database=DBName;Trusted_Connection=True; MultipleActiveResultSets=true" },
"ADSecurityGroups": { "UserSecurityGroups": "AD-DL-GROUP-NAME;AD-DL-GROUP2-NAME"},
"Logging":
{
"LogLevel": {
"Default": "Warning"
}
}
}
我的 LoginController.cs 是:
using Microsoft.Extensions.Configuration;
public class LoginController : BaseController
{
private readonly ILoginDataServices _loginDataServices;
private readonly IConfiguration _configuration;
public IActionResult Index()
{
return View();
}
public LoginController(ILoginDataServices loginDataServices, IConfiguration configuration)
{
_loginDataServices = loginDataServices;
_configuration = configuration;
}
public bool CheckLogin(string userName, string password)
{
if (CheckIfValidEmployee(userName))
{
//////checking code here....
}
else
{
return false;
}
}
bool CheckIfValidEmployee(string userName)
{
var securityGroups = _configuration.GetSection("ADSecurityGroups:UserSecurityGroups").Value.Split(';');
Console.WriteLine(securityGroups);
////////Code to check user exists into security group or not using variable value
}