所以我有一个.net Core Web Api项目和我的DBAccess类库作为一个单独的项目包含在我的解决方案中。
在appsettings.json中:
{
"ConnectionStrings": {
"DefaultConnection": "Password=L3tters&#s;Persist Security Info=True;User ID=Some_User;Initial Catalog=My_Cat;Data Source=Mt.Shasta"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
在startup.cs中我有这个:
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<IISOptions>(options =>
{
});
services.AddSingleton<IConfiguration>(Configuration);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
}
所以,在控制器中我可以做这样的事情:
private readonly string _connectionString;
public FloorController(IConfiguration configuration)
{
_connectionString = configuration.GetConnectionString("DefaultConnection");
}
_connectionString = configuration.GetConnectionString("DefaultConnection");
所有这些好东西都在SNC_GSS中:
但我需要从DBAccess获取设置... 我想创建对SNC_GSS的引用,但我不能,因为SNC_GSS已经引用了DBAccess,并且它创建了一个循环引用...
思想?
答案 0 :(得分:0)
只需使用这样的东西(构造函数注入):
public class MyClass
{
private readonly IConfiguration configuration;
public MyClass(IConfiguration configuration)
{
this.configuration = configuration;
//
configuration.GetConnectionString("DefaultConnection");
}
}
答案 1 :(得分:0)
你可以这样做:
public class AppConfigurationHelper
{
public T GetAppSettings<T>(string key) where T : class, new()
{
IConfiguration config = new ConfigurationBuilder()
.Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
.Build();
var appconfig = new ServiceCollection()
.AddOptions()
.Configure<T>(config.GetSection(key))
.BuildServiceProvider()
.GetService<IOptions<T>>()
.Value;
return appconfig;
}
}
然后使用此命名空间方法,例如:
var _AppConfigurationService = new AppConfigurationHelper();
var s = _AppConfigurationService.GetAppSettings<AppSettingsModel>("AppSettings");
当然,您需要包含该项目。
文件appsettings.json是你需要配置键值。