[英]How can I use a strongly-typed config within the Startup class
我有一个强类型配置工作,但我正在努力在“类启动”中使用强类型 class
这是我在启动时的代码:
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IHostEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
builder.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)
{
// Allow sites to hit the API
services.AddCors();
// Add Mvc Routes
services.AddMvc(option => option.EnableEndpointRouting = false);
// Add custom configuration
services.Configure<Config>(Configuration);
我想在该文件的另一个 function 中使用强类型 class ,但我不确定我该怎么做......
这是它在其他类中的工作方式:
readonly Config Config = null;
public EmailController(IOptions<Config> config)
{
Config = config.Value;
}
但是,如果我尝试将相同的代码添加到我的“类启动”中,那么我会得到这个异常
System.ArgumentNullException: '值不能是 null。 (参数'配置')'
在线上
services.Configure<Config>(Configuration);
我想您是在问如何在启动 class 中使用您的配置,然后才能将其注入构造函数?
您可以在 IConfiguration 上使用 Get 或 Bind 方法
// Add custom configuration
services.Configure<Config>(Configuration);
//Get the config object for use here
var config = Configuration.Get<Config>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.