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!

7
  • 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()? Commented Feb 16, 2018 at 22:19
  • No worries, I appreciate you taking time to help me. I updated my post with the controller code. Commented Feb 16, 2018 at 22:36
  • What you mean by not working? What exception have been thrown if so? Commented Feb 16, 2018 at 22:45
  • Seems like you need register IConfiguration for services too: services.AddSingleton<IConfiguration>(Configuration); Commented Feb 16, 2018 at 22:54
  • @Fabio, null pointer exception. See my comment in the MyService.cs code snippet. Commented Feb 16, 2018 at 23:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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/

3 Comments

I actually tried that already, and it didn't work :( I went with the options pattern as described here and that worked for me.
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.
THIS ACTUALLY WORKED!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.