简体   繁体   中英

.Net core 2 web api not injecting configuration into service

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!

Looks like you need to add a line to your ConfigureServices in your Startup.cs:

services.AddSingleton<IConfiguration>(Configuration);

Here is a full example: https://blogs.technet.microsoft.com/dariuszporowski/tip-of-the-week-how-to-access-configuration-from-controller-in-asp-net-core-2-0/

This has been working well for me.

If you need "MySettings" section added to DI, create your configuration model class MySettingsConfiguration and add this to Startup.cs

services.Configure<MySettingsConfiguration>(Configuration.GetSection("MySettings"));

This can be later used in your constructor, either with scoped service via

public MyService(IOptionsSnapshot<MySettingsConfiguration> mySettingsConfiguration) { }

or with a singleton service

public MyService(IOptions<MySettingsConfiguration> mySettingsConfiguration) { }

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM