如何阅读appsetting.json for Service Fabric解决方案?

问题描述 投票:1回答:2

我有一个Service Fabric API作为服务,业务和数据访问层是一个单独的类库。我在appsetting.json中设置配置值。但我无法读取业务层和数据访问层中的值。另外,我不想使用环境变量。如何在数据访问层和业务层中读取appsetting.json?

.net-core microservices azure-service-fabric appsettings
2个回答
1
投票

将此行添加到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;
    }

0
投票

IConfiguration object作为构造函数参数传递给API控制器。将它下游传递给其他类。

© www.soinside.com 2019 - 2024. All rights reserved.