2

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!

smoothgrips
  • 407
  • 3
  • 15
  • I apologize, I misread your initial configuration when I posted my answer. What does your controller and constructor look like where you're calling `MyMethod()`? – johnnyRose Feb 16 '18 at 22:19
  • No worries, I appreciate you taking time to help me. I updated my post with the controller code. – smoothgrips Feb 16 '18 at 22:36
  • What you mean by _not working_? What exception have been thrown if so? – Fabio Feb 16 '18 at 22:45
  • Seems like you need register `IConfiguration` for services too: `services.AddSingleton(Configuration);` – Fabio Feb 16 '18 at 22:54
  • @Fabio, null pointer exception. See my comment in the MyService.cs code snippet. – smoothgrips Feb 16 '18 at 23:38
  • @Fabio, that didn't work :( I went with the options pattern as described [here](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options) and that worked for me. – smoothgrips Feb 16 '18 at 23:39
  • I just tried to reproduce your exact setup and it is working fine for me (as expected). Are you sure that you didn’t leave something out? Can you try debugging the application and check whether the `IConfiguration` object is non-null within the Startup and in the constructor of `MyService`? – poke Feb 17 '18 at 11:12

2 Answers2

3

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.

Milan Vidakovic
  • 436
  • 5
  • 10
2

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/

Kyle Dodge
  • 834
  • 7
  • 17
  • I actually tried that already, and it didn't work :( I went with the options pattern as described [here](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options) and that worked for me. – smoothgrips Feb 16 '18 at 23:37
  • 1
    This is **not** necessary. In ASP.NET Core 2, configuration moved into DI with the WebHostBuilder, so the configuration object already is registered as a singleton. That is how the `Startup` class gets the configuration object, using DI. – poke Feb 17 '18 at 11:08
  • THIS ACTUALLY WORKED! – Aimal Khan Nov 21 '18 at 22:48