/// <summary> /// Добавление всех конфигурационных файлов в конфигурацию. /// Файлы конфигурации определяются параметром <paramref name="searchPatterns"/> /// </summary> /// <param name="builder">ConfigurationBuilder в который добавляются конфигурации.</param> /// <param name="configurationPath">Директория для поиска файлов конфигурации.</param> /// <param name="searchPatterns">Паттерны для поиска файлов.</param> /// <returns>Итоговый ConfigurationBuilder.</returns> public static IConfigurationBuilder AddConfigurationFiles(this IConfigurationBuilder builder, string configurationPath, string[] searchPatterns) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } foreach (var searchPattern in searchPatterns) { foreach (var file in Directory.EnumerateFiles(configurationPath, searchPattern, SearchOption.TopDirectoryOnly)) { var extension = Path.GetExtension(file)?.ToLower(); if (extension == ".xml") { builder = builder.AddXmlFile(file, optional: false, reloadOnChange: true); } if (extension == ".json") { // Создадим провайдер Json и обернем его в свой декоратор. var jsonConfigurationSource = new JsonConfigurationSource { Path = file.PathNormalize(), Optional = false, ReloadOnChange = true }; jsonConfigurationSource.ResolveFileProvider(); var statelessEvaluators = builder.Properties.GetValue(BuilderContext.Key.StatelessEvaluators) ?? Array.Empty <IValueEvaluator>(); builder.Add(new ProcessIncludesConfigurationSource(jsonConfigurationSource, configurationPath.PathNormalize(), statelessEvaluators)); } } } return(builder); }
protected override void ConfigureWebHost(IWebHostBuilder builder) { base.ConfigureWebHost(builder); // This is required for testing of error pages. builder.UseEnvironment(Environments.Production); builder.ConfigureAppConfiguration((_, configBuilder) => { var jsonConfigSource = new JsonConfigurationSource { Path = GetTestRunSettingsPath(), Optional = false, }; jsonConfigSource.ResolveFileProvider(); // We add TestsSettings.json before environment variables source, // leaving a chance to override connection string via environment variables. configBuilder.Sources.InsertBeforeType(jsonConfigSource, typeof(EnvironmentVariablesConfigurationSource)); if (moviesPageSize != null) { configBuilder.AddInMemoryCollection(new[] { new KeyValuePair <string, string>("moviesPageSize", moviesPageSize.Value.ToString(CultureInfo.InvariantCulture)) }); } }); builder.ConfigureLogging((hostingContext, loggingBuilder) => { loggingBuilder.ClearProviders(); loggingBuilder.AddLogging(settings => hostingContext.Configuration.Bind("logging", settings)); }); builder.ConfigureServices(services => { services.AddSingleton <IApplicationBootstrapper>(new FakeApplicationBootstrapper <MongoUser>(authenticatedUser)); // We insert DatabaseSeeder as first service, so that it is executed before UsersInitializer. services.Insert(0, ServiceDescriptor.Scoped <IApplicationInitializer, DatabaseSeeder>()); services.AddSingleton <ISeedData>(seedData); services.AddSingleton <IMovieInfoProvider>(fakeMovieInfoProviderFactory()); // Same instance should be registered for IIdGeneratorQueue and IIdGenerator. services.AddSingleton <FakeIdGenerator>(); services.AddSingleton <IIdGeneratorQueue>(sp => sp.GetRequiredService <FakeIdGenerator>()); services.AddSingleton <IIdGenerator <ObjectId> >(sp => sp.GetRequiredService <FakeIdGenerator>()); services.AddHttpsRedirection(options => { // By default test application listens for https requests on port 5001. // We must let HTTPS redirection know that the port differs from default 443, // otherwise HTTPS redirection will not happen. // https://docs.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-3.1&tabs=visual-studio#port-configuration options.HttpsPort = 5001; }); }); }
public IConfigurationProvider Build(IConfigurationBuilder builder) { var jsonConfigurationSource = new JsonConfigurationSource { Path = _filePath, Optional = true, }; jsonConfigurationSource.ResolveFileProvider(); return(new Provider(jsonConfigurationSource, _existingConfiguration)); }
public Extensions.IConfigurationProvider Build(IConfigurationBuilder builder) { var jsonSource = new JsonConfigurationSource { FileProvider = null, Path = _path, Optional = false, ReloadOnChange = false }; jsonSource.ResolveFileProvider(); var jsonProvider = jsonSource.Build(builder); return(new KeyVaultInjectingConfigurationProvider(jsonProvider, _secretInjector)); }
private static IConfigurationProvider CreateConfigurationProvider(string fullPath) { // todo: Можно расширить виды поддерживаемых провайдеров var jsonConfigurationSource = new JsonConfigurationSource { Path = fullPath }; jsonConfigurationSource.ResolveFileProvider(); var jsonConfigurationProvider = new JsonConfigurationProvider(jsonConfigurationSource); return(jsonConfigurationProvider); }
public static IConfiguration GetConfiguration(string name) { ConfigurationBuilder configBuilder = new ConfigurationBuilder(); string path = TestInternals.GetBasePath(); path = Path.Combine(path, name); JsonConfigurationSource jsonConfigurationSource = new JsonConfigurationSource() { FileProvider = null, Optional = false, Path = path }; jsonConfigurationSource.ResolveFileProvider(); configBuilder.Add(jsonConfigurationSource); return(configBuilder.Build()); }
private static void LoadConfiguration(IConfiguration currentConfiguration, IConfigurationBuilder config, string componentPath, CommandLineArgs args) { Logger.Trace(m => m("Loading hostable component using path [{0}].", componentPath)); var componentBasePath = Path.GetDirectoryName(componentPath); config.SetBasePath(componentBasePath); var configName = currentConfiguration[ConfigurationNameEnvVariable]; Logger.Info(m => m("Application was launched with configuration '{0}'.", configName)); config.LoadSharedLibraryConfigurationFiles(Logger, componentBasePath, args.SharedLibrariesPath); var configProvider = new ConfigFileNamesProvider(configName, componentBasePath); var templateValuesSource = new JsonConfigurationSource { Path = configProvider.GetTemplateValuesFile(), FileProvider = null, ReloadOnChange = false, Optional = true }; templateValuesSource.ResolveFileProvider(); var templateValuesProvider = templateValuesSource.Build(config); templateValuesProvider.Load(); foreach (var configFile in configProvider.EnumerateConfigFiles()) { config.AddJsonTemplateFile(configFile, false, false, templateValuesProvider, args.PlaceholderPattern); Logger.Trace(m => m("Configuration file [{0}] is loaded.", configFile)); } }
/// <summary> /// Adds a JSON configuration source to <paramref name="builder"/>. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="provider">The <see cref="IFileProvider"/> to use to access the file.</param> /// <param name="path">Path relative to the base path stored in /// <see cref="IConfigurationBuilder.Properties"/> of <paramref name="builder"/>.</param> /// <param name="optional">Whether the file is optional.</param> /// <param name="reloadOnChange">Whether the configuration should be reloaded if the file changes.</param> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddJsonFile(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (string.IsNullOrEmpty(path)) { throw new ArgumentException("Error_InvalidFilePath", nameof(path)); } var source = new JsonConfigurationSource { FileProvider = provider, Path = path, Optional = optional, ReloadOnChange = reloadOnChange }; source.ResolveFileProvider(); builder.Add(source); return(builder); }
private static JsonConfigurationSource CreateJsonFileSource(string directoryPath) { IFileProvider fileProvider = null; if (Directory.Exists(directoryPath)) { fileProvider = new PhysicalFileProvider(directoryPath); } var source = new JsonConfigurationSource { FileProvider = fileProvider, Path = SecretsFileName, Optional = false }; source.ResolveFileProvider(); if (source.FileProvider == null) { source.FileProvider = new PhysicalFileProvider(AppContext.BaseDirectory ?? String.Empty); } return(source); }
private static IHostBuilder PrepareHostBuilder(CommandLineArgs args) { var componentPath = Path.GetFullPath(args.Path, Directory.GetCurrentDirectory()); var builder = new HostBuilder() .ConfigureHostConfiguration( config => { config.AddEnvironmentVariables(); config.SetBasePath(AppDomain.CurrentDomain.BaseDirectory); config.AddJsonFile("hostsettings.json", true, false); ConfigureLogging(config.Build()); Logger = LogManager.GetLogger <Program>(); Logger.Trace(m => m("Starting hostbox.")); }) .ConfigureAppConfiguration( (ctx, config) => { Logger.Trace(m => m("Loading hostable component using path [{0}].", componentPath)); var componentBasePath = Path.GetDirectoryName(componentPath); config.SetBasePath(componentBasePath); var configName = ctx.Configuration[ConfigurationNameEnvVariable]; Logger.Info(m => m("Application was launched with configuration '{0}'.", configName)); config.LoadSharedLibraryConfigurationFiles(Logger, componentBasePath, args.SharedLibrariesPath); var configProvider = new ConfigFileNamesProvider(configName, componentBasePath); var templateValuesSource = new JsonConfigurationSource { Path = configProvider.GetTemplateValuesFile(), FileProvider = null, ReloadOnChange = false, Optional = true }; templateValuesSource.ResolveFileProvider(); var templateValuesProvider = templateValuesSource.Build(config); templateValuesProvider.Load(); foreach (var configFile in configProvider.EnumerateConfigFiles()) { config.AddJsonTemplateFile(configFile, false, false, templateValuesProvider, args.PlaceholderPattern); Logger.Trace(m => m("Configuration file [{0}] is loaded.", configFile)); } }) .ConfigureServices( (ctx, services) => { services .AddSingleton(provider => new ComponentConfig { Path = componentPath, SharedLibraryPath = args.SharedLibrariesPath, LoggerFactory = LogManager.GetLogger }); services.AddSingleton <IHostedService, Application>(); }); return(builder); }