本文整理汇总了C#中Microsoft.Extensions.Configuration.ConfigurationBuilder.GetSection方法的典型用法代码示例。如果您正苦于以下问题:C# ConfigurationBuilder.GetSection方法的具体用法?C# ConfigurationBuilder.GetSection怎么用?C# ConfigurationBuilder.GetSection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.Extensions.Configuration.ConfigurationBuilder
的用法示例。
在下文中一共展示了ConfigurationBuilder.GetSection方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
public static void Main(string[] args)
{
try
{
var configRoot = new ConfigurationBuilder()
.AddCs("appsettings.csx")
.Build();
// root configurations
foreach (var config in configRoot.GetChildren())
{
Console.WriteLine($"{config.Path}/{config.Key} = {config.Value}");
}
// subsection configurations
var subSection = configRoot.GetSection("e");
foreach (var config in subSection.GetChildren())
{
Console.WriteLine($"{config.Path}/{config.Key} = {config.Value}");
}
Console.WriteLine("Hello World");
}
catch (Exception e)
{
Console.WriteLine($"exception:{e.Message},{e.StackTrace}");
}
Console.Read();
}
示例2: DoWork
public async Task DoWork(CancellationToken ctx)
{
var configuration = new ConfigurationBuilder()
.AddGlobalConfigSources()
.Build();
var builder = new WebHostBuilder(configuration.GetSection("Hosting"));
var engine = builder.Build();
using (engine.Start())
{
await Task.Delay(Timeout.Infinite, ctx);
}
}
示例3: OptionsLifetimesShouldBeReplacedWithScoped
public void OptionsLifetimesShouldBeReplacedWithScoped()
{
MyApplication
.StartsFrom<DefaultStartup>()
.WithServices(services =>
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("config.json")
.Build();
services.Configure<CustomOptions>(configuration.GetSection("Options"));
services.Configure<CustomSettings>(configuration.GetSection("Settings"));
});
var options = TestApplication.Services.GetService<IOptions<CustomOptions>>();
var settings = TestApplication.Services.GetService<IOptions<CustomSettings>>();
Assert.NotNull(options);
Assert.NotNull(settings);
Assert.Equal(ServiceLifetime.Scoped, TestServiceProvider.GetServiceLifetime(typeof(IOptions<>)));
MyApplication.StartsFrom<DefaultStartup>();
}
示例4: Main
private static void Main()
{
//服务路由配置信息获取处(与Echo.Server为强制约束)。
var configuration = new ConfigurationBuilder()
.SetBasePath("d:\\")
.AddJsonFile("routes.txt", false, true)
.Build();
//客户端基本服务。
ISerializer serializer = new JsonSerializer();
IServiceIdGenerator serviceIdGenerator = new DefaultServiceIdGenerator();
var serviceRouteProvider = new DefaultServiceRouteProvider(configuration.GetSection("routes"));
var serviceRouteManager = new DefaultServiceRouteManager(new[] { serviceRouteProvider });
IAddressResolver addressResolver = new DefaultAddressResolver(serviceRouteManager);
ITransportClientFactory transportClientFactory = new NettyTransportClientFactory(serializer);
var remoteInvokeService = new RemoteInvokeService(addressResolver, transportClientFactory, serializer);
//服务代理相关。
IServiceProxyGenerater serviceProxyGenerater = new ServiceProxyGenerater(serviceIdGenerator);
var services = serviceProxyGenerater.GenerateProxys(new[] { typeof(IUserService) }).ToArray();
IServiceProxyFactory serviceProxyFactory = new ServiceProxyFactory(remoteInvokeService, serializer);
//创建IUserService的代理。
var userService = serviceProxyFactory.CreateProxy<IUserService>(services.Single(typeof(IUserService).IsAssignableFrom));
while (true)
{
Task.Run(async () =>
{
try
{
Console.WriteLine(DateTime.Now);
Console.WriteLine($"userService.GetUserName:{await userService.GetUserName(1)}");
Console.WriteLine($"userService.GetUserId:{await userService.GetUserId("rabbit")}");
Console.WriteLine($"userService.GetUserLastSignInTime:{await userService.GetUserLastSignInTime(1)}");
Console.WriteLine($"userService.Exists:{await userService.Exists(1)}");
var user = await userService.GetUser(1);
Console.WriteLine($"userService.GetUser:name={user.Name},age={user.Age}");
Console.WriteLine($"userService.Update:{await userService.Update(1, user)}");
}
catch (Exception exception)
{
Console.WriteLine("发生了错误。" + exception.Message);
}
}).Wait();
Console.ReadLine();
}
}
示例5: WithOptionsShouldSetCorrectOptions
public void WithOptionsShouldSetCorrectOptions()
{
MyApplication
.StartsFrom<DefaultStartup>()
.WithServices(services =>
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("config.json")
.Build();
services.Configure<CustomSettings>(configuration.GetSection("Settings"));
});
MyViewComponent<OptionsComponent>
.Instance()
.WithOptions(options => options
.For<CustomSettings>(settings => settings.Name = "Test"))
.InvokedWith(c => c.Invoke())
.ShouldReturn()
.View();
MyViewComponent<OptionsComponent>
.Instance()
.InvokedWith(c => c.Invoke())
.ShouldReturn()
.Content();
MyViewComponent<OptionsComponent>
.Instance()
.WithOptions(options => options
.For<CustomSettings>(settings => settings.Name = "Invalid"))
.InvokedWith(c => c.Invoke())
.ShouldReturn()
.Content();
MyApplication.StartsFrom<DefaultStartup>();
}
示例6: WithOptionsShouldSetCorrectOptions
public void WithOptionsShouldSetCorrectOptions()
{
MyApplication
.StartsFrom<TestStartup>()
.WithServices(services =>
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("config.json")
.Build();
services.Configure<CustomSettings>(configuration.GetSection("Settings"));
});
MyController<OptionsController>
.Instance()
.WithOptions(options => options
.For<CustomSettings>(settings => settings.Name = "Test"))
.Calling(c => c.Index())
.ShouldReturn()
.Ok();
MyController<OptionsController>
.Instance()
.Calling(c => c.Index())
.ShouldReturn()
.BadRequest();
MyController<OptionsController>
.Instance()
.WithOptions(options => options
.For<CustomSettings>(settings => settings.Name = "Invalid"))
.Calling(c => c.Index())
.ShouldReturn()
.BadRequest();
MyApplication.StartsFrom<DefaultStartup>();
}
示例7: AddConfiguration
public static IConfigurationRoot AddConfiguration(this IServiceCollection services)
{
// Configuration
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string>
{
{ "username", "Guest" }
})
//.AddConfigFile(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
.AddJsonFile(@"App_Data\config.json")
.AddJsonFile(@"App_Data\appsettings.json")
.AddXmlFile(@"App_Data\appsettings.xml")
.AddEntityFrameworkConfig(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)
.AddResxFile(@"App_Data\Resource1.resx")
.AddEnvironmentVariables()
.Build();
// Options (see config.json)
services.Configure<MySettings>(mySettings =>
{
mySettings.DateSetting = DateTime.Today;
});
services.Configure<MySettings>(configuration);
//services.AddSingleton<IConfigureOptions<MySettings>>(new ConfigureFromConfigurationOptions<MySettings>(configuration));
services.Configure<OtherSettings>(configuration.GetSection("otherSettings"));
// *If* you need access to generic IConfiguration this is **required**
services.AddSingleton<IConfigurationRoot>(configuration);
return configuration;
}
示例8: CoinParameters
public CoinParameters(ICoinService coinService,
string daemonUrl,
string rpcUsername,
string rpcPassword,
string walletPassword,
short rpcRequestTimeoutInSeconds)
{
var appSettings = new ConfigurationBuilder().AddJsonFile("config.json").Build().GetSection("AppSettings");
if (!string.IsNullOrWhiteSpace(daemonUrl))
{
DaemonUrl = daemonUrl;
UseTestnet = false; // this will force the CoinParameters.SelectedDaemonUrl dynamic property to automatically pick the daemonUrl defined above
IgnoreConfigFiles = true;
RpcUsername = rpcUsername;
RpcPassword = rpcPassword;
WalletPassword = walletPassword;
}
if (rpcRequestTimeoutInSeconds > 0)
{
RpcRequestTimeoutInSeconds = rpcRequestTimeoutInSeconds;
}
else
{
short rpcRequestTimeoutTryParse = 0;
if (short.TryParse(appSettings.GetSection("RpcRequestTimeoutInSeconds").Value, out rpcRequestTimeoutTryParse))
{
RpcRequestTimeoutInSeconds = rpcRequestTimeoutTryParse;
}
}
if (IgnoreConfigFiles && (string.IsNullOrWhiteSpace(DaemonUrl) || string.IsNullOrWhiteSpace(RpcUsername) || string.IsNullOrWhiteSpace(RpcPassword)))
{
throw new Exception($"One or more required parameters, as defined in {GetType().Name}, were not found in the configuration file!");
}
if (IgnoreConfigFiles && Debugger.IsAttached && string.IsNullOrWhiteSpace(WalletPassword))
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[WARNING] The wallet password is either null or empty");
Console.ResetColor();
}
#region Bitcoin
if (coinService is BitcoinService)
{
if (!IgnoreConfigFiles)
{
DaemonUrl = appSettings.GetSection("Bitcoin_DaemonUrl").Value;
DaemonUrlTestnet = appSettings.GetSection("Bitcoin_DaemonUrl_Testnet").Value;
RpcUsername = appSettings.GetSection("Bitcoin_RpcUsername").Value;
RpcPassword = appSettings.GetSection("Bitcoin_RpcPassword").Value;
WalletPassword = appSettings.GetSection("Bitcoin_WalletPassword").Value;
}
CoinShortName = "BTC";
CoinLongName = "Bitcoin";
IsoCurrencyCode = "XBT";
TransactionSizeBytesContributedByEachInput = 148;
TransactionSizeBytesContributedByEachOutput = 34;
TransactionSizeFixedExtraSizeInBytes = 10;
FreeTransactionMaximumSizeInBytes = 1000;
FreeTransactionMinimumOutputAmountInCoins = 0.01M;
FreeTransactionMinimumPriority = 57600000;
FeePerThousandBytesInCoins = 0.0001M;
MinimumTransactionFeeInCoins = 0.0001M;
MinimumNonDustTransactionAmountInCoins = 0.0000543M;
TotalCoinSupplyInCoins = 21000000;
EstimatedBlockGenerationTimeInMinutes = 10;
BlocksHighestPriorityTransactionsReservedSizeInBytes = 50000;
BaseUnitName = "Satoshi";
BaseUnitsPerCoin = 100000000;
CoinsPerBaseUnit = 0.00000001M;
}
#endregion
#region Litecoin
else if (coinService is LitecoinService)
{
if (!IgnoreConfigFiles)
{
DaemonUrl = appSettings.GetSection("Litecoin_DaemonUrl").Value;
DaemonUrlTestnet = appSettings.GetSection("Litecoin_DaemonUrl_Testnet").Value;
RpcUsername = appSettings.GetSection("Litecoin_RpcUsername").Value;
RpcPassword = appSettings.GetSection("Litecoin_RpcPassword").Value;
WalletPassword = appSettings.GetSection("Litecoin_WalletPassword").Value;
}
CoinShortName = "LTC";
CoinLongName = "Litecoin";
IsoCurrencyCode = "XLT";
//.........这里部分代码省略.........
示例9: Configure
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//load application-wide memory store
Server server = new Server();
//use session
app.UseSession();
//handle static files
var options = new StaticFileOptions {ContentTypeProvider = new FileExtensionContentTypeProvider()};
app.UseStaticFiles(options);
//exception handling
var errOptions = new DeveloperExceptionPageOptions();
errOptions.SourceCodeLineCount = 10;
app.UseDeveloperExceptionPage();
//get server info from config.json
checkForConfig();
var config = new ConfigurationBuilder()
.AddJsonFile(server.MapPath("config.json"))
.AddEnvironmentVariables().Build();
server.sqlActive = config.GetSection("Data:Active").Value;
server.sqlConnection = config.GetSection("Data:" + server.sqlActive).Value;
server.https = config.GetSection("https").Value.ToLower() == "true" ? true : false;
var isdev = false;
switch (config.GetSection("Environment").Value)
{
case "development": case "dev":
server.environment = Server.enumEnvironment.development;
isdev = true;
break;
case "staging": case "stage":
server.environment = Server.enumEnvironment.staging;
break;
case "production": case "prod":
server.environment = Server.enumEnvironment.production;
break;
}
//configure server security
server.bcrypt_workfactor = int.Parse(config.GetSection("Encryption:bcrypt_work_factor").Value);
server.CheckAdminPassword();
//run Websilk application
app.Run(async (context) =>
{
var requestStart = DateTime.Now;
DateTime requestEnd;
TimeSpan tspan;
var requestType = "";
var path = cleanPath(context.Request.Path.ToString());
var paths = path.Split('/').Skip(1).ToArray();
var extension = "";
//get request file extension (if exists)
if(path.IndexOf(".")>= 0)
{
for (int x = path.Length - 1; x >= 0; x += -1)
{
if (path.Substring(x, 1) == ".")
{
extension = path.Substring(x + 1); return;
}
}
}
server.requestCount += 1;
if (isdev)
{
Console.WriteLine("--------------------------------------------");
Console.WriteLine("{0} GET {1}", DateTime.Now.ToString("hh:mm:ss"), context.Request.Path);
}
if (paths.Length > 1)
{
if(paths[0]=="api")
{
//run a web service via ajax (e.g. /api/namespace/class/function)
IFormCollection form = null;
if(context.Request.ContentType != null)
{
if (context.Request.ContentType.IndexOf("application/x-www-form-urlencoded") >= 0)
{
}else if (context.Request.ContentType.IndexOf("multipart/form-data") >= 0)
{
//get files collection from form data
form = await context.Request.ReadFormAsync();
}
}
if (cleanNamespace(paths))
{
//execute web service
var ws = new Pipeline.WebService(server, context, paths, form);
requestType = "service";
}
//.........这里部分代码省略.........
示例10: SetUp
public void SetUp()
{
var types = new[] { typeof(User), typeof(ExtraUserInfo), typeof(UserWithExtraInfo), typeof(Usersss), typeof(House), typeof(Supervisor) };
var dbFactory = new DatabaseFactory();
var config = FluentMappingConfiguration.Scan(s =>
{
s.Assembly(typeof(User).GetTypeInfo().Assembly);
s.IncludeTypes(types.Contains);
s.PrimaryKeysNamed(y => ToLowerIf(y.Name + "Id", false));
s.TablesNamed(y => ToLowerIf(Inflector.MakePlural(y.Name), false));
s.Columns.Named(x => ToLowerIf(x.Name, false));
s.Columns.ForceDateTimesToUtcWhere(x => x.GetMemberInfoType() == typeof(DateTime) || x.GetMemberInfoType() == typeof(DateTime?));
s.Columns.ResultWhere(y => ColumnInfo.FromMemberInfo(y).ResultColumn);
s.OverrideMappingsWith(new FluentMappingOverrides());
s.OverrideMappingsWith(new OneToManyMappings());
});
dbFactory.Config().WithFluentConfig(config);
var configuration = new ConfigurationBuilder()
.AddJsonFile("config.json")
.Build();
var testDBType = Convert.ToInt32(configuration.GetSection("TestDBType").Value);
switch (testDBType)
{
case 1: // SQLite In-Memory
TestDatabase = new InMemoryDatabase();
Database = dbFactory.Build(new Database(TestDatabase.Connection));
break;
case 2: // SQL Local DB
case 3: // SQL Server
var dataSource = configuration.GetSection("TestDbDataSource").Value;
TestDatabase = new SQLLocalDatabase(dataSource);
Database = dbFactory.Build(new Database(TestDatabase.Connection, new SqlServer2008DatabaseType()));
break;
case 4: // SQL CE
case 5: // MySQL
case 6: // Oracle
case 7: // Postgres
Assert.Fail("Database platform not supported for unit testing");
return;
#if !DNXCORE50
case 8: // Firebird
TestDatabase = new FirebirdDatabase();
var db = new Database(TestDatabase.Connection, new FirebirdDatabaseType());
db.Mappers.Insert(0, new FirebirdDefaultMapper());
Database = dbFactory.Build(db);
break;
#endif
default:
Assert.Fail("Unknown database platform specified");
return;
}
InsertData();
}
示例11: BuildServiceProvider
private IServiceProvider BuildServiceProvider()
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("../../src/ImgAzyobuziNet/appsettings.json")
.Build();
var services = new ServiceCollection()
.Configure<ImgAzyobuziNetOptions>(configuration.GetSection("ImgAzyobuziNet"))
.AddLogging()
.AddCaching();
return services
.AddInstance(typeof(ITestActivator), new TestActivator(services.BuildServiceProvider()))
.BuildServiceProvider();
}
示例12: SetUp
public void SetUp()
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("config.json")
.Build();
var testDBType = Convert.ToInt32(configuration.GetSection("TestDBType").Value);
switch (testDBType)
{
case 1: // SQLite In-Memory
TestDatabase = new InMemoryDatabase();
Database = new Database(TestDatabase.Connection);
break;
case 2: // SQL Local DB
TestDatabase = new SQLLocalDatabase();
Database = new Database(TestDatabase.Connection, new SqlServer2008DatabaseType() { UseOutputClause = false }, SqlClientFactory.Instance, IsolationLevel.ReadUncommitted); // Need read uncommitted for the transaction tests
break;
case 3: // SQL Server
case 4: // SQL CE
case 5: // MySQL
case 6: // Oracle
case 7: // Postgres
Assert.Fail("Database platform not supported for unit testing");
return;
#if !DNXCORE50
case 8: // Firebird
TestDatabase = new FirebirdDatabase();
Database = new Database(TestDatabase.Connection, new FirebirdDatabaseType(), FirebirdClientFactory.Instance, IsolationLevel.ReadUncommitted);
break;
#endif
default:
Assert.Fail("Unknown database platform specified");
return;
}
// Insert test data
InsertData();
}
示例13: SetUp
public void SetUp()
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("config.json")
.Build();
testDBType = Convert.ToInt32(configuration.GetSection("TestDBType").Value);
switch (testDBType)
{
case 1: // SQLite In-Memory
TestDatabase = new InMemoryDatabase();
break;
case 2: // SQL Local DB
var dataSource = configuration.GetSection("TestDbDataSource").Value;
TestDatabase = new SQLLocalDatabase(dataSource);
break;
case 3: // SQL Server
case 4: // SQL CE
case 5: // MySQL
case 6: // Oracle
case 7: // Postgres
Assert.Fail("Database platform not supported for unit testing");
return;
#if !DNXCORE50
case 8: // Firebird
TestDatabase = new FirebirdDatabase();
break;
#endif
default:
Assert.Fail("Unknown database platform specified: " + testDBType);
return;
}
}