user2927217
user2927217

Reputation: 53

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?

Upvotes: 1

Views: 2183

Answers (2)

heavenwing
heavenwing

Reputation: 598

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;
    }

Upvotes: 4

LoekD
LoekD

Reputation: 11470

Pass the IConfiguration object as constructor argument to your API controller. Pass it downstream to other classes.

Upvotes: 0

Related Questions