I have a strongly-typed config working but I am struggling with using the strongly-typed class within the "class Startup"
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...
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. (Parameter 'config')'
on the line
services.Configure<Config>(Configuration);
CodePudding user response:
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?
You can use Get or Bind methods on IConfiguration
// Add custom configuration
services.Configure<Config>(Configuration);
//Get the config object for use here
var config = Configuration.Get<Config>();