Search code examples
.net-coremicroservicesazure-service-fabricappsettings

How to read appsetting.json for Service Fabric solution?


I have a Service Fabric API as service, and business and data access layers are a separate class library. I set the configuration values in the appsetting.json. But I am not able to read the values in the business layer and data access layers. Also, I don't want to use the environment variables. How can I read the appsetting.json in data access layer and business layer?


Solution

  • add this line into CreateServiceInstanceListeners

            protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
        {
            return new ServiceInstanceListener[]
            {
                new ServiceInstanceListener(serviceContext =>
                    new KestrelCommunicationListener(serviceContext, "ServiceEndpoint", (url, listener) =>
                    {
                        ServiceEventSource.Current.ServiceMessage(serviceContext, $"Starting Kestrel on {url}");
    
                        return new WebHostBuilder()
                                    .UseKestrel()
                                    .UseCommonConfiguration()
                                    .ConfigureServices(
                                        services => services
                                            .AddSingleton<StatelessServiceContext>(serviceContext))
                                    .UseContentRoot(Directory.GetCurrentDirectory())
                                    .UseStartup<Startup>()
                                    .UseServiceFabricIntegration(listener, ServiceFabricIntegrationOptions.None)
                                    .UseUrls(url)
                                    .Build();
                    }))
            };
        }
    

    UseCommonConfiguration

            public static IWebHostBuilder UseCommonConfiguration(this IWebHostBuilder builder)
        {
            builder.ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env = hostingContext.HostingEnvironment;
    
                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
    
                if (env.IsDevelopment())
                {
                    var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
                    if (appAssembly != null)
                    {
                        config.AddUserSecrets(appAssembly, optional: true);
                    }
                }
    
                config.AddEnvironmentVariables();
            });
    
            return builder;
        }