For some reason that I can't pin down, DI is not working with configuration in my .Net core 2 web api. Here's the code:
Program.cs:
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
Startup.cs:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<IMyService, MyService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
My controller:
public class MyController : Controller
{
private readonly IMyService service;
public MyController(IMyService service)
{
this.service = service;
}
[HttpGet]
public IActionResult Get()
{
return Ok(service.MyMethod());
}
}
My service:
public class MyService : IMyService
{
private readonly IConfiguration config;
public MyService(IConfiguration config)
{
this.config = config;
}
public string MyMethod()
{
var test = config["MySetting"]; // <-- Breaks here. config is null.
}
}
I've read through the configuration docs here and through SO posts like this one and cannot seem to figure out why DI is not working for me. Any thoughts? Something I'm missing? Thanks!