本文整理汇总了C#中ServiceCollection.AddOptions方法的典型用法代码示例。如果您正苦于以下问题:C# ServiceCollection.AddOptions方法的具体用法?C# ServiceCollection.AddOptions怎么用?C# ServiceCollection.AddOptions使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ServiceCollection
的用法示例。
在下文中一共展示了ServiceCollection.AddOptions方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ManageControllerTest
public ManageControllerTest()
{
var efServiceProvider = new ServiceCollection().AddEntityFrameworkInMemoryDatabase().BuildServiceProvider();
var services = new ServiceCollection();
services.AddOptions();
services
.AddDbContext<MusicStoreContext>(b => b.UseInMemoryDatabase().UseInternalServiceProvider(efServiceProvider));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<MusicStoreContext>();
services.AddLogging();
services.AddOptions();
// IHttpContextAccessor is required for SignInManager, and UserManager
var context = new DefaultHttpContext();
context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature() { Handler = new TestAuthHandler() });
services.AddSingleton<IHttpContextAccessor>(
new HttpContextAccessor()
{
HttpContext = context,
});
_serviceProvider = services.BuildServiceProvider();
}
示例2: Main
public async Task Main()
{
var services = new ServiceCollection();
services.AddDefaultServices(defaultProvider);
services.AddAssembly(typeof(Program).GetTypeInfo().Assembly);
services.AddOptions();
services.AddSingleton(x => MemoryCache.INSTANCE);
services.AddLogging();
services.AddGlobalConfiguration(environment);
var provider = services.BuildServiceProvider();
var logging = provider.GetService<ILoggerFactory>();
logging.AddProvider(provider.GetService<ISNSLoggerProvider>());
logging.AddConsole();
var cancellationSource = new CancellationTokenSource();
var taskRunner = new TaskRunner(logging.CreateLogger<TaskRunner>(), provider);
var tasks = taskRunner.RunTasksFromAssembly(typeof(Program).GetTypeInfo().Assembly, cancellationSource.Token);
Console.CancelKeyPress += (sender, e) =>
{
Console.WriteLine("Caught cancel, exiting...");
cancellationSource.Cancel();
};
await Task.WhenAll(tasks);
}
示例3: ResolvePolicy_DefaultKeyLifetime
public void ResolvePolicy_DefaultKeyLifetime()
{
IServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddOptions();
RunTestWithRegValues(serviceCollection, new Dictionary<string, object>()
{
["DefaultKeyLifetime"] = 1024 // days
});
var services = serviceCollection.BuildServiceProvider();
var keyManagementOptions = services.GetService<IOptions<KeyManagementOptions>>();
Assert.Equal(TimeSpan.FromDays(1024), keyManagementOptions.Value.NewKeyLifetime);
}
示例4: ConfigureRouting_ConfiguresOptionsProperly
public void ConfigureRouting_ConfiguresOptionsProperly()
{
// Arrange
var services = new ServiceCollection();
services.AddOptions();
// Act
services.AddRouting(options => options.ConstraintMap.Add("foo", typeof(TestRouteConstraint)));
var serviceProvider = services.BuildServiceProvider();
// Assert
var accessor = serviceProvider.GetRequiredService<IOptions<RouteOptions>>();
Assert.Equal("TestRouteConstraint", accessor.Value.ConstraintMap["foo"].Name);
}
示例5: GetAuthorizationContext
private AuthorizationContext GetAuthorizationContext(Action<ServiceCollection> registerServices, bool anonymous = false)
{
var basicPrincipal = new ClaimsPrincipal(
new ClaimsIdentity(
new Claim[] {
new Claim("Permission", "CanViewPage"),
new Claim(ClaimTypes.Role, "Administrator"),
new Claim(ClaimTypes.Role, "User"),
new Claim(ClaimTypes.NameIdentifier, "John")},
"Basic"));
var validUser = basicPrincipal;
var bearerIdentity = new ClaimsIdentity(
new Claim[] {
new Claim("Permission", "CupBearer"),
new Claim(ClaimTypes.Role, "Token"),
new Claim(ClaimTypes.NameIdentifier, "John Bear")},
"Bearer");
var bearerPrincipal = new ClaimsPrincipal(bearerIdentity);
validUser.AddIdentity(bearerIdentity);
// ServiceProvider
var serviceCollection = new ServiceCollection();
if (registerServices != null)
{
serviceCollection.AddOptions();
serviceCollection.AddLogging();
registerServices(serviceCollection);
}
var serviceProvider = serviceCollection.BuildServiceProvider();
// HttpContext
var httpContext = new Mock<HttpContext>();
var auth = new Mock<AuthenticationManager>();
httpContext.Setup(o => o.Authentication).Returns(auth.Object);
httpContext.SetupProperty(c => c.User);
if (!anonymous)
{
httpContext.Object.User = validUser;
}
httpContext.SetupGet(c => c.RequestServices).Returns(serviceProvider);
auth.Setup(c => c.AuthenticateAsync("Bearer")).ReturnsAsync(bearerPrincipal);
auth.Setup(c => c.AuthenticateAsync("Basic")).ReturnsAsync(basicPrincipal);
auth.Setup(c => c.AuthenticateAsync("Fails")).ReturnsAsync(null);
// AuthorizationContext
var actionContext = new ActionContext(
httpContext: httpContext.Object,
routeData: new RouteData(),
actionDescriptor: new ActionDescriptor());
var authorizationContext = new AuthorizationContext(
actionContext,
Enumerable.Empty<IFilterMetadata>().ToList()
);
return authorizationContext;
}
示例6: GetHttpContext
private static HttpContext GetHttpContext()
{
var httpContext = new DefaultHttpContext();
httpContext.Response.Body = new MemoryStream();
var services = new ServiceCollection();
services.AddOptions();
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
httpContext.RequestServices = services.BuildServiceProvider();
return httpContext;
}
示例7: BuildHostingServices
private IServiceCollection BuildHostingServices()
{
_options = new WebHostOptions(_config);
var appEnvironment = PlatformServices.Default.Application;
var contentRootPath = ResolveContentRootPath(_options.ContentRootPath, appEnvironment.ApplicationBasePath);
var applicationName = _options.ApplicationName ?? appEnvironment.ApplicationName;
// Initialize the hosting environment
_hostingEnvironment.Initialize(applicationName, contentRootPath, _options);
var services = new ServiceCollection();
services.AddSingleton(_hostingEnvironment);
if (_loggerFactory == null)
{
_loggerFactory = new LoggerFactory();
}
foreach (var configureLogging in _configureLoggingDelegates)
{
configureLogging(_loggerFactory);
}
//The configured ILoggerFactory is added as a singleton here. AddLogging below will not add an additional one.
services.AddSingleton(_loggerFactory);
//This is required to add ILogger of T.
services.AddLogging();
services.AddTransient<IApplicationBuilderFactory, ApplicationBuilderFactory>();
services.AddTransient<IHttpContextFactory, HttpContextFactory>();
services.AddOptions();
var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore");
services.AddSingleton<DiagnosticSource>(diagnosticSource);
services.AddSingleton<DiagnosticListener>(diagnosticSource);
// Conjure up a RequestServices
services.AddTransient<IStartupFilter, AutoRequestServicesStartupFilter>();
// Ensure object pooling is available everywhere.
services.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();
if (!string.IsNullOrEmpty(_options.StartupAssembly))
{
try
{
var startupType = StartupLoader.FindStartupType(_options.StartupAssembly, _hostingEnvironment.EnvironmentName);
if (typeof(IStartup).GetTypeInfo().IsAssignableFrom(startupType.GetTypeInfo()))
{
services.AddSingleton(typeof(IStartup), startupType);
}
else
{
services.AddSingleton(typeof(IStartup), sp =>
{
var hostingEnvironment = sp.GetRequiredService<IHostingEnvironment>();
var methods = StartupLoader.LoadMethods(sp, startupType, hostingEnvironment.EnvironmentName);
return new ConventionBasedStartup(methods);
});
}
}
catch (Exception ex)
{
var capture = ExceptionDispatchInfo.Capture(ex);
services.AddSingleton<IStartup>(_ =>
{
capture.Throw();
return null;
});
}
}
foreach (var configureServices in _configureServicesDelegates)
{
configureServices(services);
}
return services;
}
示例8: CreateDefaultServiceCollection
private ServiceCollection CreateDefaultServiceCollection(
Action<DepsOptions> configureOptions = null,
string depsFileName = null,
bool isDevelopment = false)
{
var services = new ServiceCollection();
services.AddOptions();
services.AddSingleton<IMemoryCache>(new MemoryCache(new OptionsWrapper<MemoryCacheOptions>(new MemoryCacheOptions())));
services.Configure<DepsOptions>((opts) =>
{
//opts.WebRoot = "testwebroot/";
if (depsFileName != null)
{
opts.DepsFileName = depsFileName;
}
});
services.Configure(
configureOptions ??
((DepsOptions _) => { }));
var path = Path.GetFullPath(Path.GetDirectoryName(Path.Combine(Path.GetFullPath("testwebroot"), "../../../../../")));
var webrootPath = Path.Combine(path, "testwebroot");
var approotPath = Path.Combine(path, "testapproot");
var env = new Mock<IHostingEnvironment>();
env.Setup(m => m.ContentRootPath).Returns(path);
env
.Setup(m => m.EnvironmentName)
.Returns(isDevelopment ? EnvironmentName.Development : EnvironmentName.Production);
env.Setup(m => m.WebRootPath).Returns(webrootPath);
env.Setup(m => m.WebRootFileProvider).Returns(new PhysicalFileProvider(webrootPath));
services.AddSingleton(env.Object);
var appRootFileProviderAccessor = new Mock<IAppRootFileProviderAccessor>();
appRootFileProviderAccessor
.Setup(m => m.AppRootFileProvider)
.Returns(new PhysicalFileProvider(approotPath));
services.AddSingleton(appRootFileProviderAccessor.Object);
var httpContextAccessor = new Mock<IHttpContextAccessor>();
httpContextAccessor.Setup(m => m.HttpContext).Returns((HttpContext)null);
services.AddSingleton(httpContextAccessor.Object);
var matcherMock = new Mock<Matcher>();
matcherMock.Setup(m => m.AddInclude(It.IsAny<string>())).Returns((string _) => matcherMock.Object);
matcherMock.Setup(m => m.AddExclude(It.IsAny<string>())).Returns((string _) => matcherMock.Object);
matcherMock.Setup(m => m.Execute(It.IsAny<DirectoryInfoBase>())).Returns((DirectoryInfoBase _) => new PatternMatchingResult(new FilePatternMatch[0]));
services.AddSingleton(matcherMock.Object);
services.AddSingleton<DepsManager>();
return services;
}
示例9: CreateVirtualPathContext
private static VirtualPathContext CreateVirtualPathContext(
RouteValueDictionary values,
Action<RouteOptions> options = null,
string routeName = null)
{
var services = new ServiceCollection();
services.AddSingleton<ILoggerFactory>(NullLoggerFactory.Instance);
services.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();
services.AddOptions();
services.AddRouting();
if (options != null)
{
services.Configure<RouteOptions>(options);
}
var context = new DefaultHttpContext
{
RequestServices = services.BuildServiceProvider(),
};
return new VirtualPathContext(
context,
ambientValues: null,
values: values,
routeName: routeName);
}
示例10: CreateServices
private IServiceProvider CreateServices()
{
var services = new ServiceCollection();
services.AddOptions();
services.AddRouting();
return services.BuildServiceProvider();
}
示例11: GetHttpContext
private static HttpContext GetHttpContext()
{
var httpContext = new DefaultHttpContext();
var services = new ServiceCollection();
services.AddOptions();
httpContext.RequestServices = services.BuildServiceProvider();
return httpContext;
}
示例12: GetServiceCollection
private static ServiceCollection GetServiceCollection(IStringLocalizerFactory localizerFactory)
{
var serviceCollection = new ServiceCollection();
serviceCollection
.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>()
.AddSingleton<ILoggerFactory>(new NullLoggerFactory())
.AddSingleton<UrlEncoder>(new UrlTestEncoder());
serviceCollection.AddOptions();
serviceCollection.AddRouting();
serviceCollection.AddSingleton<IInlineConstraintResolver>(
provider => new DefaultInlineConstraintResolver(provider.GetRequiredService<IOptions<RouteOptions>>()));
if (localizerFactory != null)
{
serviceCollection.AddSingleton<IStringLocalizerFactory>(localizerFactory);
}
return serviceCollection;
}
示例13: GetInitialServiceCollection
private static IServiceCollection GetInitialServiceCollection()
{
var serviceCollection = new ServiceCollection();
var diagnosticSource = new DiagnosticListener(TestFrameworkName);
var applicationLifetime = new ApplicationLifetime();
// default server services
serviceCollection.AddSingleton(Environment);
serviceCollection.AddSingleton<IApplicationLifetime>(applicationLifetime);
serviceCollection.AddSingleton<ILoggerFactory>(LoggerFactoryMock.Create());
serviceCollection.AddLogging();
serviceCollection.AddTransient<IApplicationBuilderFactory, ApplicationBuilderFactory>();
serviceCollection.AddTransient<IHttpContextFactory, HttpContextFactory>();
serviceCollection.AddOptions();
serviceCollection.AddSingleton<DiagnosticSource>(diagnosticSource);
serviceCollection.AddSingleton(diagnosticSource);
serviceCollection.AddTransient<IStartupFilter, AutoRequestServicesStartupFilter>();
serviceCollection.AddTransient<IServiceProviderFactory<IServiceCollection>, DefaultServiceProviderFactory>();
serviceCollection.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();
return serviceCollection;
}
示例14: ServiceCollectionConfigurationIsRetainedInRootContainer
public void ServiceCollectionConfigurationIsRetainedInRootContainer()
{
var collection = new ServiceCollection();
collection.AddOptions();
collection.Configure<TestOptions>(options =>
{
options.Value = 5;
});
var builder = new ContainerBuilder();
builder.Populate(collection);
var container = builder.Build();
var resolved = container.Resolve<IOptions<TestOptions>>();
Assert.NotNull(resolved.Value);
Assert.Equal(5, resolved.Value.Value);
}
示例15: CreateServices
private static IServiceProvider CreateServices()
{
var services = new ServiceCollection();
services.AddOptions();
services.AddLogging();
services.AddRouting();
services
.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>()
.AddSingleton<UrlEncoder>(UrlEncoder.Default);
return services.BuildServiceProvider();
}