当前位置: 首页>>代码示例>>C#>>正文


C# ServiceCollection.AddOptions方法代码示例

本文整理汇总了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();
        }
开发者ID:Cream2015,项目名称:MusicStore,代码行数:26,代码来源:ManageControllerTest.cs

示例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);
        }
开发者ID:alanedwardes,项目名称:aeblog,代码行数:30,代码来源:Program.cs

示例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);
        }
开发者ID:supermason,项目名称:DataProtection,代码行数:13,代码来源:RegistryPolicyResolverTests.cs

示例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);
        }
开发者ID:leloulight,项目名称:Routing,代码行数:14,代码来源:RouteOptionsTests.cs

示例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;
        }
开发者ID:phinq19,项目名称:git_example,代码行数:62,代码来源:AuthorizeFilterTest.cs

示例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;
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:12,代码来源:JsonResultTest.cs

示例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;
        }
开发者ID:akrisiun,项目名称:Hosting,代码行数:82,代码来源:WebHostBuilder.cs

示例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;
		}
开发者ID:mrahhal,项目名称:MR.AspNet.Deps,代码行数:55,代码来源:DepsManagerTest.cs

示例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);
        }
开发者ID:Corays,项目名称:Routing,代码行数:26,代码来源:RouteCollectionTest.cs

示例10: CreateServices

 private IServiceProvider CreateServices()
 {
     var services = new ServiceCollection();
     services.AddOptions();
     services.AddRouting();
     return services.BuildServiceProvider();
 }
开发者ID:phinq19,项目名称:git_example,代码行数:7,代码来源:MvcAreaRouteBuilderExtensionsTest.cs

示例11: GetHttpContext

        private static HttpContext GetHttpContext()
        {
            var httpContext = new DefaultHttpContext();
            var services = new ServiceCollection();
            services.AddOptions();
            httpContext.RequestServices = services.BuildServiceProvider();

            return httpContext;
        }
开发者ID:phinq19,项目名称:git_example,代码行数:9,代码来源:JsonViewComponentResultTest.cs

示例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;
        }
开发者ID:ymd1223,项目名称:Mvc,代码行数:21,代码来源:RemoteAttributeTest.cs

示例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;
        }
开发者ID:ivaylokenov,项目名称:MyTested.AspNetCore.Mvc,代码行数:27,代码来源:TestApplication.cs

示例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);
        }
开发者ID:arronchen,项目名称:Autofac,代码行数:17,代码来源:AutofacRegistrationTests.cs

示例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();
        }
开发者ID:cemalshukriev,项目名称:Mvc,代码行数:12,代码来源:UrlHelperTest.cs


注:本文中的ServiceCollection.AddOptions方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。