[英]How can I use a strongly-typed config within the Startup class
I have a strongly-typed config working but I am struggling with using the strongly-typed class within the "class Startup"我有一个强类型配置工作,但我正在努力在“类启动”中使用强类型 class
Here is my code in startup:这是我在启动时的代码:
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);
I'd like to use the strongly-typed class in another function in that file, but I'm not sure how I can do that...我想在该文件的另一个 function 中使用强类型 class ,但我不确定我该怎么做......
This is how it works in other classes:这是它在其他类中的工作方式:
readonly Config Config = null;
public EmailController(IOptions<Config> config)
{
Config = config.Value;
}
But if I try to add the same code to my "class Startup" then I get this exception但是,如果我尝试将相同的代码添加到我的“类启动”中,那么我会得到这个异常
System.ArgumentNullException: 'Value cannot be null.
System.ArgumentNullException: '值不能是 null。 (Parameter 'config')'
(参数'配置')'
on the line在线上
services.Configure<Config>(Configuration);
I think you are asking how can you use your config inside the startup class before you are allowed to inject it into a constructor?我想您是在问如何在启动 class 中使用您的配置,然后才能将其注入构造函数?
You can use Get or Bind methods on IConfiguration您可以在 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.