Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mvc core 2.0, how to use an appSettings.json file via configuration

Today I was trying out the new asp.net core 2.0 but ran into some trouble using a JSON configuration file that I wasnt to inject in IConfiguration configuration constructor property.

In asp.net core 1.1 I would use this following code in StartUp:

public static IConfigurationRoot Configuration;

Public Startup(IHostingEnvironment env) {
     var builder = new ConfigurationBuilder()
     .SetBasePath(env.ContentRootPath)
     .AddJsonFile("appSettings.json", optional: false, reloadOnChange: true)

  Configuration = builder.Build();
}

and could access it from the code like:

private string _mailTo = Startup.Configuration["mailSettings:mailToAddress"];

However In Core 2.0 they changed to IConfiguration and it's already defined moreover I don't see any way i can use the configuration in my other classes, so I'm kinda clueless on how to proceed.

The startupClass:

    using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc.Formatters;
using NLog.Web;
using NLog.Extensions.Logging;
using cityInfoTestApi.Services;

namespace cityInfoTestApi
{
    public class Startup
    {

        public IConfiguration Configuration { get; private set; }

        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            Configuration = configuration;
            env.ConfigureNLog("nlog.config");
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
                .AddMvcOptions(o => o.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()));




        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddNLog();
            app.AddNLogWeb();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStatusCodePages();
            app.UseMvc();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });


        }
    }
}

my json file:

{
    "mailSetings": {
        "mailToAddress": "[email protected]",
        "mailFromAddress":  "[email protected]"
    }
}

my custom class wanting to use the settings (note it was how i would use core 1.1:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace cityInfoTestApi.Services
{
    public class LocalMailService : IMailService
    {

        private string _mailTo = Startup.Configuration["mailSettings:mailToAddress"];
        private string _mailFrom = Startup.Configuration["mailSettings:mailFromAddress"];


        public void Send(string subject, string message)
        {
            Debug.WriteLine($"Mail from {_mailFrom} to {_mailTo}, with LocalMailService");
            Debug.WriteLine($"Subject: {subject}");
            Debug.WriteLine($"Message: {message}");
        }
    }
}

any help would be much appreciated, Cheers!

like image 841
Rodney Wormsbecher Avatar asked Dec 24 '22 13:12

Rodney Wormsbecher


1 Answers

Yes, ASP.NET Core 2.0 has changed the way for configuration building. You need to use IWebHostBuilder.ConfigureAppConfiguration method now.

Add something like this to your IWebHost creation in Program.cs:

.ConfigureAppConfiguration((builderContext, config) =>
{
    IHostingEnvironment env = builderContext.HostingEnvironment;

    config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
})

Then IConfiguration instance may be injected to your Startup class via constructor as a dependency (or any other class, thanks to DI mechanism):

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
       Configuration = configuration;
    }
    ...
 }

There is a good article that describes those changes: ASP.NET Core 2.0 Configuration Changes


Regarding your way to get access to settings from custom classes (like LocalMailService) - avoid using any static dependencies. This broken DI conception used in ASP.NET Core. Read about using IOptions feature instead. Or you may again use DI and get IConfiguration instance via ctor in LocalMailService.

like image 144
Set Avatar answered May 21 '23 18:05

Set