Esempio n. 1
0
 private static void AddUserConfiguration(string AssemblyName, IAppConfigSections UserConfiguration)
 {
     lock (locker)
     {
         // Ensure key doesn't already exist
         if (!_userConfiguration.ContainsKey(AssemblyName))
         {
             _userConfiguration.Add(AssemblyName, UserConfiguration);
         }
     }
 }
Esempio n. 2
0
        private static IAppConfigSections FindConfiguration(string AssemblyName)
        {
            IAppConfigSections userConfiguration = null;

            lock (locker)
            {
                if (_userConfiguration.ContainsKey(AssemblyName))
                {
                    userConfiguration = _userConfiguration[AssemblyName];
                }
            }

            return(userConfiguration);
        }
        /// <summary>
        /// This method will create an initialize a generic Host Builder
        /// </summary>
        /// <typeparam name="TApp">Main application type. Used to access user secrets</typeparam>
        /// <param name="args">Application arguments</param>
        /// <param name="localServiceConfiguration">Delegate to be executed to add any non-standard configuration needs</param>
        /// <returns>Configured IHostBuilder</returns>
        public static IHostBuilder CreateHostBuilder <TApp>(string[] args, ConfigureLocalServices <TApp> localServiceConfiguration = null) where TApp : class
        {
            IApplicationSecrets            appSecrets      = null;
            IApplicationSetupConfiguration appIntialConfig = null;
            IAppConfigSections             sections        = null;

            IHostBuilder hostBuilder = Host.CreateDefaultBuilder(args)
                                       .ConfigureAppConfiguration((hostingContext, builder) =>
            {
                sections        = ConfigFactory.Initialize <TApp>(hostingContext, builder);
                appSecrets      = sections.appSecrets;
                appIntialConfig = sections.appIntialConfig;
            })
                                       .ConfigureServices((hostingContext, services) =>
            {
                localServiceConfiguration?.Invoke(hostingContext, services, sections);

                services
                .AddTransient <TApp>()
                .AddSingleton <IApplicationSetupConfiguration>(sp =>
                {
                    return(appIntialConfig);
                })
                .AddSingleton <IApplicationSecrets>(sp =>
                {
                    return(appSecrets);
                })
                .AddSingleton <IHostEnvironment>(sp =>
                {
                    return(hostingContext.HostingEnvironment);
                })
                .AddSingleton <IApplicationRequirements <TApp>, ApplicationRequirements <TApp> >();

                services.BuildServiceProvider();
            })
                                       .ConfigureLogging((hostingContext, logging) =>
            {
                ConfigureCustomLogging(hostingContext, logging, appSecrets, appIntialConfig);
            });

            return(hostBuilder);
        }
        /// <summary>
        /// If the default factory method "ConsoleHostBuilderHelper.CreateApp" does not support all the services
        /// you need at runtime, then you can add them here. "CreateApp" calls this method before any other services
        /// are added to the IServiceCollection.
        /// </summary>
        /// <param name="hostingContext"></param>
        /// <param name="services"></param>
        public static void ConfigureLocalServices(HostBuilderContext hostingContext, IServiceCollection services, IAppConfigSections sections)
        {
            // Register the appropriate interfaces depending on the environment
            bool useKeyVaultKey = !string.IsNullOrEmpty(sections.appIntialConfig.KeyVaultKey);

            ConfigureFileStorage.Initialize(useKeyVaultKey, services);
            ConfigureServiceBus.Initialize(useKeyVaultKey, services);
            ConfigureApplicationCache.Initialize(useKeyVaultKey, services);
        }
Esempio n. 5
0
        /// <summary>
        /// Provides the user the opportunity to initialize the user configuration
        /// </summary>
        /// <param name="context">HostBuilderContext</param>
        /// <param name="builder">IConfigurationBuilder</param>
        /// <param name="CurrentAssembly">The assembly where the "UserSecretsId" exists in the .csproj file</param>
        /// <returns>IAppConfigSections</returns>
        public static IAppConfigSections Initialize(HostBuilderContext context, IConfigurationBuilder builder, Assembly CurrentAssembly = null)
        {
            IAppConfigSections retVal = null;

            // If the user did not specify the assembly that contains the "UserSecretsId" configuration
            // then assume its the entry assembly
            if (CurrentAssembly == null)
            {
                CurrentAssembly = Assembly.GetEntryAssembly();
            }

            string AssemblyName = CurrentAssembly.FullName;

            retVal = FindConfiguration(AssemblyName);
            if (retVal == null)
            {
                retVal = new AppConfigSections();

                // NOTE: The order in which we add to the configuration builder will
                //       determine the order of override. So in this case the settings
                //       in the "appsettings.json" file are used first, if a user-secret
                //       with the same name is provided then it will override the value
                //       in the .json file. And finally, if an environment variable
                //       with the same name is found then it will override the user-secret.
                if (builder == null)
                {
                    builder = new ConfigurationBuilder();
                }

                builder.SetBasePath(Directory.GetCurrentDirectory());

                // Bind the configuration properties to the properties in the SettingsConfig object
                var initialConfig = builder.Build();
                IConfigurationSection myInitialConfig = initialConfig.GetSection(InitialConfigurationSectionName);
                _appSetupConfig = new InitialConfiguration();
                myInitialConfig.Bind(_appSetupConfig);

                // Override appsettings.json properties with user secrets and Azure KeyVault settings.
                try
                {
                    builder.AddUserSecrets(CurrentAssembly);
                }
                catch (Exception Err)
                {
                }

                if (!string.IsNullOrEmpty(_appSetupConfig.KeyVaultName) && !string.IsNullOrEmpty(_appSetupConfig.KeyVaultKey))
                {
                    // Substitute the runtime environment name in the keyvault properties
                    _appSetupConfig.KeyVaultName = _appSetupConfig.KeyVaultName.Replace("{RTE}", _appSetupConfig.RTE);
                    _appSetupConfig.KeyVaultKey  = _appSetupConfig.KeyVaultKey.Replace("{RTE}", _appSetupConfig.RTE);

                    builder.AddAzureKeyVault(_appSetupConfig.KeyVaultName);
                }

                // Build the final configuration
                _baseConfiguration = builder.Build();

                // Set the IApplicationSecrets from the KeyVault if found, otherwise
                // grab it from appsettings.json/secrets.json
                retVal.appSecrets      = InitializeApplicationSecrets(_baseConfiguration, _appSetupConfig);
                retVal.appIntialConfig = _appSetupConfig;

                // Use the KeyVault secrets connect to redis cache
                _cache = _baseConfiguration.InitializeRedisCache(retVal.appSecrets);

                // Set up automated refresh from redis cache. "TimedCacheRefresh" configuration
                // setting determines which keys are read from the cache and how often they are read.
                // These values are then placed as regular values that can be read from IConfiguration
                _cache?.RefreshConfigurationFromCache(retVal.appSecrets, _baseConfiguration);

                // Save the configuration so we don't have to create it again
                AddUserConfiguration(AssemblyName, retVal);
            }

            return(retVal);
        }