Configuration in ASP.NET Core

less than 1 minute read

When you create stateless service fabric core api, the template doesn’t add configuration builder by default. I’ve spent about an hour pulling my hair why it doesn’t load appsettings.json on start up. So, Add it first.

// from CreateServiceInstanceListeners()
return new WebHostBuilder()
                (context, config) => config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true))
                services => services
            .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)

If you want typed config setting, create a settings class

public class SfUris
    public string QueryService { get; set; }
    public string CommandService { get; set; }

This class will be newed up by Services collection in startup.

services.AddSingleton(r => r.GetRequiredService<IOptions<SfUris>>().Value);

By returning the type with IOptions().Value, you can get the object populated from the config.

Then you can use the typed config setting.

services.AddTransient(x => x.GetService<IProxyFactory>()