本文整理汇总了C#中Microsoft.Extensions.Configuration.ConfigurationBuilder.AddInMemoryCollection方法的典型用法代码示例。如果您正苦于以下问题:C# ConfigurationBuilder.AddInMemoryCollection方法的具体用法?C# ConfigurationBuilder.AddInMemoryCollection怎么用?C# ConfigurationBuilder.AddInMemoryCollection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.Extensions.Configuration.ConfigurationBuilder
的用法示例。
在下文中一共展示了ConfigurationBuilder.AddInMemoryCollection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Build
public IHostingEngine Build()
{
var configBuider = new ConfigurationBuilder();
configBuider.AddInMemoryCollection(new Dictionary<string, string> {{"server.urls", uri}});
var builder = new WebHostBuilder(configBuider.Build());
builder.UseStartup(app => { new Startup().ConfigureApplication(app); }, services => { new ServiceConfigurer(documentStore).ConfigureServices(services); });
builder.UseServer("Microsoft.AspNet.Server.Kestrel");
return builder.Build();
}
示例2: IdentityOptionsFromConfig
public void IdentityOptionsFromConfig()
{
const string roleClaimType = "rolez";
const string usernameClaimType = "namez";
const string useridClaimType = "idz";
const string securityStampClaimType = "stampz";
var dic = new Dictionary<string, string>
{
{"identity:claimsidentity:roleclaimtype", roleClaimType},
{"identity:claimsidentity:usernameclaimtype", usernameClaimType},
{"identity:claimsidentity:useridclaimtype", useridClaimType},
{"identity:claimsidentity:securitystampclaimtype", securityStampClaimType},
{"identity:user:requireUniqueEmail", "true"},
{"identity:password:RequiredLength", "10"},
{"identity:password:RequireNonAlphanumeric", "false"},
{"identity:password:RequireUpperCase", "false"},
{"identity:password:RequireDigit", "false"},
{"identity:password:RequireLowerCase", "false"},
{"identity:lockout:AllowedForNewUsers", "FALSe"},
{"identity:lockout:MaxFailedAccessAttempts", "1000"}
};
var builder = new ConfigurationBuilder();
builder.AddInMemoryCollection(dic);
var config = builder.Build();
Assert.Equal(roleClaimType, config["identity:claimsidentity:roleclaimtype"]);
var services = new ServiceCollection();
services.AddIdentity<TestUser,TestRole>();
services.Configure<IdentityOptions>(config.GetSection("identity"));
var accessor = services.BuildServiceProvider().GetRequiredService<IOptions<IdentityOptions>>();
Assert.NotNull(accessor);
var options = accessor.Value;
Assert.Equal(roleClaimType, options.ClaimsIdentity.RoleClaimType);
Assert.Equal(useridClaimType, options.ClaimsIdentity.UserIdClaimType);
Assert.Equal(usernameClaimType, options.ClaimsIdentity.UserNameClaimType);
Assert.Equal(securityStampClaimType, options.ClaimsIdentity.SecurityStampClaimType);
Assert.True(options.User.RequireUniqueEmail);
Assert.Equal("ab[email protected]+", options.User.AllowedUserNameCharacters);
Assert.False(options.Password.RequireDigit);
Assert.False(options.Password.RequireLowercase);
Assert.False(options.Password.RequireNonAlphanumeric);
Assert.False(options.Password.RequireUppercase);
Assert.Equal(10, options.Password.RequiredLength);
Assert.False(options.Lockout.AllowedForNewUsers);
Assert.Equal(1000, options.Lockout.MaxFailedAccessAttempts);
}
示例3: Main
public static void Main(string[] args = null)
{
ConfigurationBuilder configurationBuilder =
new ConfigurationBuilder();
if (args == null)
{
// Add defaultConfigurationStrings
configurationBuilder.AddInMemoryCollection(
DefaultConfigurationStrings);
}
else
{
configurationBuilder
.AddInMemoryCollection(DefaultConfigurationStrings)
.AddJsonFile("Config.json",
true) // bool indicates file is optional
// "EssentialDotNetConfiguration" is an optional prefix for all
// environment configuration keys
.AddEnvironmentVariables("EssentialDotNetConfiguration")
.AddCommandLine(
args, GetSwitchMappings(DefaultConfigurationStrings));
}
Configuration = configurationBuilder.Build();
Console.WriteLine($"Hello {Configuration["Profile:UserName"]}");
ConsoleWindow consoleWindow =
Configuration.Get<ConsoleWindow>("AppConfiguration:MainWindow");
ConsoleWindow.SetConsoleWindow(consoleWindow);
}
示例4: DefaultConfigurationBuilder
/// <summary>Creates a default configuration builder with some defaults.</summary>
public static ConfigurationBuilder DefaultConfigurationBuilder()
{
var builder = new ConfigurationBuilder();
builder.AddInMemoryCollection(new Dictionary<string, string>
{
{ nameof(DataConnectionString), "UseDevelopmentStorage=true" },
{ nameof(LogsFolder), "logs" },
{ nameof(TraceToConsole), "true" },
{ nameof(InitialSilosCount), "2" },
});
return builder;
}
示例5: Create
public static TestServer Create(Action<IApplicationBuilder> configureApp, Action<IServiceCollection> configureServices = null)
{
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddInMemoryCollection(new []
{
new KeyValuePair<string, string>("webroot", ".")
});
var builder = new WebApplicationBuilder()
.UseConfiguration(configurationBuilder.Build())
.Configure(configureApp)
.ConfigureServices(configureServices);
return new TestServer(builder);
}
示例6: ConfigSummarySnippet
public ConfigSummarySnippet()
{
// Everything between SNIPPET-START and SNIPPET-END will be inlined in the doc!
// SNIPPET-START
var builder = new ConfigurationBuilder();
builder.AddInMemoryCollection();
var config = builder.Build();
config["somekey"] = "somevalue";
// do some other work
var setting = config["somekey"]; // also returns "somevalue"
// SNIPPET-END
}
示例7: Create
public static StartupServer Create(Uri baseAddress = null)
{
var appEnv = CallContextServiceLocator.Locator.ServiceProvider.GetRequiredService<IApplicationEnvironment>();
var config = new ConfigurationBuilder();
var configDict = new Dictionary<string, string>();
configDict["Hosting:Environment"] = "Test";
config.AddInMemoryCollection(configDict.AsEnumerable());
var conf = config.Build();
var env = new HostingEnvironment();
env.Initialize($"{appEnv.ApplicationBasePath}/../../src/Accounting", conf);
var startup = new Accounting.Startup(appEnv, env);
var setup = new SetupObject();
Action<IApplicationBuilder> buildApp = (app) =>
{
app.Use(async (context, next) =>
{
var req = context.Request;
if (req.Path == testSetupPathString && setup.Setup != null)
{
await setup.Setup(context);
}
else
{
await next();
}
});
startup.Configure(app);
};
Action<IServiceCollection> buildServices = (services) =>
{
startup.ConfigureServices(services);
services.Remove(services.Where(sp => sp.ServiceType == typeof(IConfigureOptions<AntiforgeryOptions>)).First());
services.TryAddEnumerable(ServiceDescriptor.Transient<IConfigureOptions<AntiforgeryOptions>, TestAntiforgeryOptionsSetup>());
services.AddSingleton<IAntiforgeryTokenSerializer, TestAntiforgeryTokenSerializer>();
services.AddSingleton<IAntiforgeryTokenGenerator, TestAntiforgeryTokenGenerator>();
};
StartupServer server = new StartupServer(CreateBuilder(conf, app => buildApp(app), services => buildServices(services)));
server.setupObject = setup;
server.BaseAddress = baseAddress;
return server;
}
示例8: ResolvePlaceholders_ResolvesSinglePlaceholder
public void ResolvePlaceholders_ResolvesSinglePlaceholder()
{
// Arrange
string text = "foo=${foo}";
ConfigurationBuilder builder = new ConfigurationBuilder();
var dic1 = new Dictionary<string, string>()
{
{"foo", "bar"}
};
builder.AddInMemoryCollection(dic1);
var config = builder.Build();
// Act and Assert
string result = PropertyPlaceholderHelper.ResovlePlaceholders(text, config);
Assert.Equal("foo=bar", result);
}
示例9: StartWebSocketServer
private IWebHost StartWebSocketServer(Func<HttpContext, Task> app)
{
Action<IApplicationBuilder> startup = builder =>
{
builder.Use(async (ct, next) =>
{
try
{
// Kestrel does not return proper error responses:
// https://github.com/aspnet/KestrelHttpServer/issues/43
await next();
}
catch (Exception ex)
{
if (ct.Response.HasStarted)
{
throw;
}
ct.Response.StatusCode = 500;
ct.Response.Headers.Clear();
await ct.Response.WriteAsync(ex.ToString());
}
});
builder.UseWebSockets();
builder.Run(c => app(c));
};
var configBuilder = new ConfigurationBuilder();
configBuilder.AddInMemoryCollection();
var config = configBuilder.Build();
config["server.urls"] = "http://localhost:54321";
var host = new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.Configure(startup)
.Build();
host.Start();
return host;
}
示例10: IdentityOptionsActionOverridesConfig
public void IdentityOptionsActionOverridesConfig()
{
var dic = new Dictionary<string, string>
{
{"identity:user:requireUniqueEmail", "true"},
{"identity:lockout:MaxFailedAccessAttempts", "1000"}
};
var builder = new ConfigurationBuilder();
builder.AddInMemoryCollection(dic);
var config = builder.Build();
var services = new ServiceCollection();
services.Configure<IdentityOptions>(config.GetSection("identity"));
services.AddIdentity<TestUser, TestRole>(o => { o.User.RequireUniqueEmail = false; o.Lockout.MaxFailedAccessAttempts++; });
var accessor = services.BuildServiceProvider().GetRequiredService<IOptions<IdentityOptions>>();
Assert.NotNull(accessor);
var options = accessor.Value;
Assert.False(options.User.RequireUniqueEmail);
Assert.Equal(1001, options.Lockout.MaxFailedAccessAttempts);
}
示例11: Main
public static void Main(string[] args)
{
var builder = new ConfigurationBuilder();
Console.WriteLine("Initial Config Sources: " + builder.Sources.Count());
builder.AddInMemoryCollection(new Dictionary<string, string>
{
{ "username", "Guest" }
});
Console.WriteLine("Added Memory Source. Sources: " + builder.Sources.Count());
builder.AddCommandLine(args);
Console.WriteLine("Added Command Line Source. Sources: " + builder.Sources.Count());
var config = builder.Build();
string username = config["username"];
Console.WriteLine($"Hello, {username}!");
}
示例12: ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
/* configure specifying settings */
var builder = new ConfigurationBuilder();
builder.AddInMemoryCollection()
.AddEnvironmentVariables();
var config = builder.Build();
config["ConnectionStringDefault"] =
"Server=(localdb)\\MSSQLLocalDB;Database=BooksDB;Trusted_Connection=true;MultipleActiveResultSets=true";
var paths = config["BookWebPictures"];
config["PicturesFolderProd"] = Path.Combine(paths, "Prod");
config["PicturesFolderSeed"] = Path.Combine(paths, "Seed");
/* configure providing settings */
services.AddOptions();
services.Configure<ConnectionString>(config);
services.Configure<PicturesFolder>(config);
services.AddMvc(conf =>
{
#if !DEBUG
conf.Filters.Add(new RequireHttpsAttribute());
#endif
});
services.AddIdentity<BookWebUser, IdentityRole>(conf =>
{
// TODO configure
}).AddEntityFrameworkStores<BookWebContext>()
.AddDefaultTokenProviders();
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<BookWebContext>(/*options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]*/);
services.AddScoped<BookWebContext>();
services.AddTransient<DataSeeder>();
}
示例13: SetConfigurationDefaults
private static void SetConfigurationDefaults(ConfigurationBuilder builder)
{
var defaults = new Dictionary<string, string>
{
{"configuration:ChromeDriverLocation", "C:\\Selenium\\chromedriver_win32"},
{"configuration:IEDriverLocation", "C:\\Selenium\\iedriver_win32"}
};
builder.AddInMemoryCollection(defaults);
}
示例14: GetConfiguration
private static IConfigurationRoot GetConfiguration(IDictionary<string, string> data)
{
var configurationBuilder = new Microsoft.Extensions.Configuration.ConfigurationBuilder();
configurationBuilder.AddInMemoryCollection(data);
return configurationBuilder.Build();
}
示例15: ResolvePlaceholders_ResolvesMultipleRecursiveInPlaceholders
public void ResolvePlaceholders_ResolvesMultipleRecursiveInPlaceholders()
{
// Arrange
string text1 = "foo=${b${inner}}";
ConfigurationBuilder builder1 = new ConfigurationBuilder();
var dic1 = new Dictionary<string, string>()
{
{"bar", "bar"},
{"inner", "ar"}
};
builder1.AddInMemoryCollection(dic1);
var config1 = builder1.Build();
string text2 = "${top}";
ConfigurationBuilder builder2 = new ConfigurationBuilder();
var dic2 = new Dictionary<string, string>()
{
{"top", "${child}+${child}"},
{"child", "${${differentiator}.grandchild}" },
{"differentiator", "first" },
{"first.grandchild", "actualValue" }
};
builder2.AddInMemoryCollection(dic2);
var config2 = builder2.Build();
// Act and Assert
string result1 = PropertyPlaceholderHelper.ResovlePlaceholders(text1, config1);
Assert.Equal("foo=bar", result1);
string result2 = PropertyPlaceholderHelper.ResovlePlaceholders(text2, config2);
Assert.Equal("actualValue+actualValue", result2);
}