App Settings .Net Core
Asked Answered
H

2

1

I am trying to add an appsettings.json and followed a lot of tutorials and still can not do it.

I create appsettings.json

{
  "option1": "value1_from_json",

  "ConnectionStrings": {
    "DefaultConnection": "Server=,\\SQL2016DEV;Database=DBName;Trusted_Connection=True"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

Add my class:

public class MyOptions
{
    public string Option1 { get; set; }
}

public class ConnectionStringSettings
{
    public string DefaultConnection { get; set; }
}

then on my Startup.cs

public IConfiguration Configuration { get; set; }

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
                        .SetBasePath(env.ContentRootPath)
                        .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

    if (env.IsDevelopment())
    {
        builder.AddUserSecrets<Startup>();
    }

    builder.AddEnvironmentVariables();
    Configuration = builder.Build();
}

and :

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddScoped<IDataService<Sale>, DataService<Sale>>();

    // add My services
    // Register the IConfiguration instance which MyOptions binds against.
    services.AddOptions();

    // Load the data from the 'root' of the json file
    services.Configure<MyOptions>(Configuration);

    // load the data from the 'ConnectionStrings' section of the json file
    var connStringSettings = Configuration.GetSection("ConnectionStrings");
    services.Configure<ConnectionStringSettings>(connStringSettings); 
}

and also injected the Dependency into the controller constructor.

public class ForecastApiController : Controller
{
    private IDataService<Sale> _SaleDataService;
    private readonly MyOptions _myOptions;

    public ForecastApiController(IDataService<Sale> service, IOptions<MyOptions> optionsAccessor)
    {
        _SaleDataService = service;
        _myOptions = optionsAccessor.Value;
        var valueOfOpt1 = _myOptions.Option1;
    }
}

EDITED: The problem is that I get Configuration underlined in red

 services.Configure<MyOptions>(Configuration); 

Error CS1503
Argument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfiguration' to 'System.Action Exercise.Models.MyOptions

I know there are similar questions explaining how to: ASP.NET Core MVC App Settings

but it doesn't work for me

Cheers

Highspirited answered 14/2, 2018 at 1:3 Comment(11)
If it's underlined, hit ctrl+. and see what it tells you. Are you missing this line? IConfigurationRoot Configuration { get; }Wharve
Yes, and now i get: Error CS1503 Argument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfiguration' to 'System.Action<OPSIexercise.Models.MyOptions>'Highspirited
That's the sort of bug I see when I have a bracket or semicolon missing or extra.Wharve
Sorry, I edited the question with the new error message regarding your commentHighspirited
I think you have a similar bug (incorrect brackets) in your Controller. Also, how do you know that the History field isn't being set by the Configuration? You've set var window, but you don't use it in the code you're showing.Wharve
Actually, I think I've got an idea. Try putting a subsection in your appsettings, like { "ConfigStrings": { "History" 14 } }. Then call services.Configure<MyOptions>(Configuration.GetSection("ConfigStrings"))Wharve
@AleGarcia ConfigureServices is called before Configure You are building the Configuration too late in the startup class. The linked question is doing it in the class constructor.Ministry
not sure but I copy the code from linked question I get the same errorHighspirited
You should build your config in the Startup constructor or even in Program.cs and then inject it into Startup.Ballocks
Yes I have done it but still same error, i fact Im going to edit my question to include the constructor and the build. cheersHighspirited
Is there a reason why you are using ASP.NET Core 1.x instead of 2.0?Designed
G
4

Did you include the correct namespace?

using Microsoft.Extensions.DependencyInjection;

Also did you have a reference to?:

Microsoft.Extensions.Options.ConfigurationExtensions

In above Assembly we have:

public static IServiceCollection Configure<TOptions>(this IServiceCollection services, IConfiguration config) where TOptions : class;

Most probably you are using the extension method from Microsoft.Extensions.Options assembly (which is wrong)

public static IServiceCollection Configure<TOptions>(this IServiceCollection services, Action<TOptions> configureOptions) where TOptions : class;
Geanine answered 14/2, 2018 at 6:1 Comment(2)
Ha! Also did you have a reference to?: Microsoft.Extensions.Options.ConfigurationExtensionsHighspirited
Just a tip: Use the Meta package in Future at least for developement. It makes our life so much easier ;) learn.microsoft.com/en-us/aspnet/core/fundamentals/metapackageGeanine
N
0

Make sure that you imported everything that is necessary and have the required packages installed. Then you can do the following

services.Configure<MyOptions>(options => Configuration.GetSection("options1").Bind(options)); 

this will cause the options to be updated at runtime whenever you change the appssettings programatically.

Necrophilism answered 14/2, 2018 at 8:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.