NibblyPig
NibblyPig

Reputation: 52932

What is the purpose of the Configure method of IServiceCollection when you can DI settings without it?

I've done this:

services.Configure<ApplicationSettings>(_configuration.GetSection("ApplicationSettings"));

I assumed that would allow me to inject ApplicationSettings, but apparently not.

I could just do GetSection(...) and register it as a singleton, but then what's the point of .Configure?

The msdn doc says "Registers a configuration instance that TOptions will bind against, and updates the options when the configuration changes."

It's unclear how to set up the pattern to use the config as DI in my application though.

This is the SO question I was trying to implement:

How do I transform appsettings.json in a .NET Core MVC project?

Upvotes: 18

Views: 8998

Answers (1)

Vlad DX
Vlad DX

Reputation: 4730

This exact thing configures a dependency injection for the strongly-typed settings section ApplicationSettings.

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.Configure<ApplicationSettings>(_configuration.GetSection("ApplicationSettings"));

    // You can register your service
    services.AddTransient<SomeService>();
}

Then you implement the service and you have the settings section automatically injected into it.

public class SomeService
{
    private readonly IOptions<ApplicationSettings> _options;

    public SomeService(IOptions<ApplicationSettings> options)
    {
        _options = options;
    }

    public string AddPrefix(string value)
    {
        // AddPrefix("test value")
        // will return:
        // PREFIX - test value
        return $"{_options.Value.Prefix} - {value}";
    }
}

Given that you have your ApplicationSettings defined as:

public class ApplicationSettings
{
    public string Prefix { get; set; }
}

And your appsettings.json should look like:

{
    "ApplicationSettings": {
        "Prefix": "PREFIX"
    }
}

Upvotes: 8

Related Questions