[英]ASP.NET Core: Accessing appsettings from another project in solution
In my Startup.cs
class I have the following config build which initializes the db context: 在我的
Startup.cs
类中,我有以下配置构建,它初始化db上下文:
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",true)
.AddEnvironmentVariables();
Configuration = builder.Build();
NHibernateUnitOfWork.Init(Configuration["ConnectionStrings:OracleConnection"]);
NHibernateUnitOfWork
is located in a different project as a class library project. NHibernateUnitOfWork
作为类库项目位于不同的项目中。 I want to be able to inject (or somehow pass the settings) instead of using the NHibernateUnitOfWork.Init
in my Startup.cs
class. 我希望能够注入(或以某种方式传递设置),而不是在我的
Startup.cs
类中使用NHibernateUnitOfWork.Init
。
I can build the appsettings in my class library but trying to avoid that. 我可以在我的类库中构建appsettings但是试图避免这种情况。
What is a sane way to do this ? 什么是理智的方式来做到这一点?
You can inject it. 你可以注射它。
In your Startup.cs
class, you can add the following to your ConfigureServices(IServiceCollection services)
method: 在
Startup.cs
类中,可以将以下内容添加到ConfigureServices(IServiceCollection services)
方法中:
services.AddSingleton(Configuration);
From there, you can use constructor injection and consume it downstream the same way you normally would: 从那里,您可以使用构造函数注入并以与通常相同的方式向下游使用它:
public class SomeClass
{
public SomeClass(IConfigurationRoot configuration)
{
NHibernateUnitOfWork.Init(Configuration["ConnectionStrings:OracleConnection"]);
}
}
NOTE: This assumes Configuration
is defined in your Startup.cs
class: 注意:这假定
Configuration
在Startup.cs
类中定义:
public static IConfigurationRoot Configuration;
See this: Read appsettings json values in .NET Core Test Project 请参阅: 在.NET Core Test Project中读取appsettings json值
Essentially this is an integration solution using the TestServer. 基本上这是使用TestServer的集成解决方案。 But if you're having to use the configuration, then it should probably be an integration test anyway.
但是如果你不得不使用配置,那么无论如何它应该是一个集成测试。
The key to using the config in your main project inside your test project is the following: 在测试项目中的主项目中使用配置的关键如下:
"buildOptions": {
"copyToOutput": {
"include": [ "appsettings.Development.json" ]
}
}
which needs to go inside your main project's project.json 需要进入主项目的project.json
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.