Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot set Configuration from JSON appsettings file in .NET Core project

Since there's no ConfigurationManager class in .NET Core, now I have to set config in appsettings.json instead web.config

According to this blog post I have to set my configuration there, so I did like this:

{   "Logging": {     "IncludeScopes": false,     "LogLevel": {       "Default": "Debug",       "System": "Information",       "Microsoft": "Information"     }   },    "Conexion": {     "name" : "empresas",     "connectionString": "Data Source=empresas;Initial Catalog=CATALMA; Integrated Security=True;",     "providerName": "System.Data.SqlClient"   } } 

I just writed that "Conexion".

Now I created in a ViewModels folder the following class:

public class ConexionConfig      {        public string name { get; set; }         public string connectionString { get; set; }         public string providerName { get; set; }     } 

Now, In Startup.cs, in the ConfigureServices method, I have to add it by:

public void ConfigureServices(IServiceCollection services)         {             // Add framework services.             services.Configure<ConexionConfig>(Configuration.GetSection("Conexion"));             services.AddMvc();         } 

But unfortunately, I get the following error:

Argument 2: cannot convert from       'Microsoft.Extensions.Configuration.IConfigurationSection' to      'System.Action<ConexionConfig>' 

What am I missing?

like image 785
Mr_LinDowsMac Avatar asked Jul 21 '16 23:07

Mr_LinDowsMac


1 Answers

Firstly, you need to add the following nuget package to your ASP Core Project.

Microsoft.Extensions.Options.ConfigurationExtensions 

The extension methods contained in the package will allow you to configure the strongly typed configuration the way you originally wanted to do it.

services.Configure<ConexionConfig>(Configuration.GetSection("Conexion")); 

Alternatively, you could use the binder directly like another answer in this thread suggests without important the previous package but rather:

Microsoft.Extensions.Configuration.Binder 

This means that you would have to explicitly enable the options on the pipeline, and bind the action. That is:

services.AddOptions(); services.Configure<ConexionConfig>(x => Configuration.GetSection("Conexion").Bind(x)); 
like image 116
Sarel Esterhuizen Avatar answered Oct 13 '22 17:10

Sarel Esterhuizen