コード例 #1
0
        public void CanResolveUsingCustomParser()
        {
            var count = 0;

            var options = ConfigurationOptions.Create();

            options.WithParser((type, parser) =>
            {
                type.ShouldBe(typeof(SomeDecimalSetting));
                parser.ShouldNotBeNull();
                count.ShouldBe(0);
                count++;
                return(parser);
            });

            // Chaining multiple functions
            options.WithParser((type, parser) =>
            {
                type.ShouldBe(typeof(SomeDecimalSetting));
                parser.ShouldNotBeNull();
                count.ShouldBe(1);
                return(parser);
            });

            var configurationFactory = ConfigurationFactoryCreator.Create(options);

            SomeDecimalSetting config = configurationFactory.CreateConfigurationSetting(typeof(SomeDecimalSetting));

            config.Value.ShouldBeOfType <decimal>();
            config.Value.Equals(decimal.Parse("1.2345")).ShouldBeTrue();
        }
コード例 #2
0
ファイル: Startup.cs プロジェクト: dasiths/NimbleConfig
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(Configuration); // This is needed if you want to use the same config instance built in the constructor,
            // Else it will use the default one from the webhost builder
            // https://stackoverflow.com/questions/46574521/is-services-addsingletoniconfiguration-really-needed-in-net-core-2-api

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Throw an exception if missing settings are being used
            var configOptions = ConfigurationOptions.Create()
                                .WithExceptionForMissingSettings();

            // Wire up our settings
            services.AddConfigurationSettings()
            .WithSingletonInstances()
            .UsingOptionsIn(configOptions)
            .UsingLogger <MyConfigLogger>()
            .AndBuild();

            // Or use the built in console logger like this:
            //.UsingLogger<ConsoleConfigLogger>()

            // Note: You can use .WithScopedInstances() for per request inatance of settings
            // This works great withg the 'reloadOnChange' option for appsettings.json files

            services.AddLogging();
        }
コード例 #3
0
        public static IConfigurationFactory Create(IConfigurationOptions options = null)
        {
            // Construct the IConfiguration
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");

            var configuration = (IConfiguration)builder.Build();

            // Configure the core pieces
            var keynameResolver     = new KeyNameResolver();
            var parserResolver      = new ParserResolver();
            var configResolver      = new ConfigurationReaderResolver();
            var constructorResolver = new ValueConstructorResolver();

            options = options ?? ConfigurationOptions.Create();

            var configuratinFactory = new ConfigurationFactory(configuration,
                                                               options,
                                                               keynameResolver,
                                                               configResolver,
                                                               parserResolver,
                                                               constructorResolver);

            return(configuratinFactory);
        }
コード例 #4
0
 public ConfigInjectionBuilder(IServiceCollection services)
 {
     _services       = services ?? throw new ArgumentNullException(nameof(services));
     SettingLifetime = ServiceLifetime.Singleton;
     Options         = ConfigurationOptions.Create();
     Assemblies      = new[] { Assembly.GetEntryAssembly() };
     LoggerType      = null;
 }
コード例 #5
0
        public void AndBuild()
        {
            if (_isBuilt)
            {
                return;
            }

            _isBuilt = true;

            // Add required default resolvers as singletons
            _services.AddSingleton <IResolver <IKeyName>, KeyNameResolver>();
            _services.AddSingleton <IResolver <IParser>, ParserResolver>();
            _services.AddSingleton <IResolver <IConfigurationReader>, ConfigurationReaderResolver>();
            _services.AddSingleton <IResolver <IValueConstructor>, ValueConstructorResolver>();

            // Add configuration options instance
            Options = Options ?? ConfigurationOptions.Create();
            _services.AddSingleton <IConfigurationOptions>((s) => Options);

            // Construct the configuration factory service descriptor
            var configDescriptor = new ServiceDescriptor(typeof(IConfigurationFactory),
                                                         typeof(ConfigurationFactory),
                                                         SettingLifetime);

            _services.Add(configDescriptor);

            // Get the setting types in the assemblies specified
            var settingTypes = SettingScanner.GetConfigurationSettings(Assemblies);

            // If an ignore list is specified
            if (IgnoreTypes != null)
            {
                settingTypes = settingTypes.Except(IgnoreTypes);
            }

            foreach (var settingType in settingTypes)
            {
                // Construct our service descriptor
                var settingDescriptor = new ServiceDescriptor(settingType,
                                                              (s) =>
                {
                    var factory = s.GetService <IConfigurationFactory>();
                    return(factory.CreateConfigurationSetting(settingType));
                },
                                                              SettingLifetime);

                _services.Add(settingDescriptor);
            }

            if (LoggerType != null)
            {
                _services.AddSingleton(typeof(IConfigLogger), LoggerType);
            }
        }
コード例 #6
0
        public void MissingComplexSettingThrowsException()
        {
            var options = ConfigurationOptions.Create();

            options.MissingConfigurationStratergy = MissingConfigurationStratergy.ThrowException;

            _configurationFactory = ConfigurationFactoryCreator.Create(options);

            Should.Throw <ConfigurationSettingMissingException>(() =>
            {
                _configurationFactory.CreateConfigurationSetting(typeof(SomeUnresolvedComplexSetting));
            });
        }
コード例 #7
0
        private static IConfigurationFactory Create(IConfiguration configuration, IConfigurationOptions options = null)
        {
            configuration.EnsureNotNull(nameof(configuration));

            // Configure the core pieces
            var keynameResolver     = new KeyNameResolver();
            var parserResolver      = new ParserResolver();
            var configResolver      = new ConfigurationReaderResolver();
            var constructorResolver = new ValueConstructorResolver();

            options = options ?? ConfigurationOptions.Create();

            var configuratinFactory = new ConfigurationFactory(configuration,
                                                               options,
                                                               keynameResolver,
                                                               configResolver,
                                                               parserResolver,
                                                               constructorResolver);

            return(configuratinFactory);
        }
コード例 #8
0
        public void CanResolveSettingWithCustomName()
        {
            var options = ConfigurationOptions.Create();

            options.WithNamingScheme((type, name) =>
            {
                if (type == typeof(SomeDecimalSetting))
                {
                    return(new KeyName("SomeSection:", name.QualifiedKeyName));
                }

                return(name);
            });

            var configurationFactory = ConfigurationFactoryCreator.Create(options);

            SomeDecimalSetting config = configurationFactory.CreateConfigurationSetting(typeof(SomeDecimalSetting));

            config.Value.ShouldBeOfType <decimal>();
            config.Value.Equals(decimal.Parse("0.12345")).ShouldBeTrue();
        }
コード例 #9
0
        public static ServiceProvider SetupConfigurationDependencies(this IConfiguration configuration,
                                                                     Assembly[] assemblies,
                                                                     IConfigurationOptions configurationOptions = null)
        {
            // Configure your DI Container
            // We are using 'Microsoft.Extensions.DependencyInjection' in this example
            // but you can use your favourite one like Autofac, StructureMap, Ninject etc

            var services = new ServiceCollection();

            // Add single IConfiguration
            services.AddSingleton(configuration);

            // Add configuration options instance
            configurationOptions = configurationOptions ?? ConfigurationOptions.Create();
            services.AddSingleton <IConfigurationOptions>((s) => configurationOptions);

            // Add required resolvers
            services.AddSingleton <IResolver <IKeyName>, KeyNameResolver>();
            services.AddSingleton <IResolver <IParser>, ParserResolver>();
            services.AddSingleton <IResolver <IConfigurationReader>, ConfigurationReaderResolver>();
            services.AddSingleton <IResolver <IValueConstructor>, ValueConstructorResolver>();

            // Add configuration factory
            services.AddSingleton <IConfigurationFactory, ConfigurationFactory>();

            var settingTypes = GetConfigurationSettings(assemblies);

            foreach (var settingType in settingTypes)
            {
                services.AddSingleton(settingType, (s) =>
                {
                    var factory = s.GetService <IConfigurationFactory>();
                    return(factory.CreateConfigurationSetting(settingType));
                });
            }

            return(services.BuildServiceProvider());
        }