【发布时间】:2017-09-06 01:18:59
【问题描述】:
我已将 appsettings.json 文件的访问权限添加为我的 Startup.cs 中的框架服务:
public IConfigurationRoot Configuration { get; }
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.Configure<AppConfig>(Configuration);
services.AddMvc();
}
所以现在我可以从我的控制器访问配置文件了:
public class HomeController : Controller
{
private readonly AppConfig _appConfig;
public HomeController(IOptions<AppConfig> appConfig, ConfigContext configContext)
{
_appConfig = appConfig.Value;
}
}
这行得通,但目前在 netcoreapps 中从我的控制器范围之外的类访问配置文件的良好做法是什么?
我的意思是我不想总是将所需的配置变量传递给其他方法,例如:
public IActionResult AnyAction() {
SomeStaticClass.SomeMethod(_appConfig.var1, _appConfig.var2, _appConfig.var3...)
//or always have to pass the _appConfig reference
SomeStaticClass.SomeMethod(_appConfig)
}
在以前版本的 .NET Framework 中,如果我需要从“SomeStaticClass”访问配置文件,我曾经在需要访问 web.config 的任何类中使用 ConfigurationManager。
在 netcoreapp1.1 中正确的做法是什么? ConfigurationManager 之类的方法或依赖注入方法都适合我。
【问题讨论】:
-
好的,我想我应该创建一个类,将配置文件公开为框架的服务,以便我可以在任何地方使用它
标签: asp.net-core asp.net-core-mvc asp.net-core-1.1