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


C# ServiceCollection.BuildServiceProvider方法代码示例

本文整理汇总了C#中Microsoft.Framework.DependencyInjection.ServiceCollection.BuildServiceProvider方法的典型用法代码示例。如果您正苦于以下问题:C# ServiceCollection.BuildServiceProvider方法的具体用法?C# ServiceCollection.BuildServiceProvider怎么用?C# ServiceCollection.BuildServiceProvider使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.Framework.DependencyInjection.ServiceCollection的用法示例。


在下文中一共展示了ServiceCollection.BuildServiceProvider方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: OnValidateIdentityRejectsWhenValidateSecurityStampFails

        public async Task OnValidateIdentityRejectsWhenValidateSecurityStampFails()
        {
            var user = new IdentityUser("test");
            var httpContext = new Mock<HttpContext>();
            var userManager = MockHelpers.MockUserManager<IdentityUser>();
            var authManager = new Mock<IAuthenticationManager>();
            var claimsManager = new Mock<IClaimsIdentityFactory<IdentityUser>>();
            var signInManager = new Mock<SignInManager<IdentityUser>>(userManager.Object,
                authManager.Object, claimsManager.Object);
            signInManager.Setup(s => s.ValidateSecurityStamp(It.IsAny<ClaimsIdentity>(), user.Id)).ReturnsAsync(null).Verifiable();
            var services = new ServiceCollection();
            services.AddInstance(signInManager.Object);
            httpContext.Setup(c => c.ApplicationServices).Returns(services.BuildServiceProvider());
            var id = new ClaimsIdentity(ClaimsIdentityOptions.DefaultAuthenticationType);
            id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

            var ticket = new AuthenticationTicket(id, new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow });
            var context = new CookieValidateIdentityContext(httpContext.Object, ticket, new CookieAuthenticationOptions());
            Assert.NotNull(context.Properties);
            Assert.NotNull(context.Options);
            Assert.NotNull(context.Identity);
            await
                SecurityStampValidator.OnValidateIdentity<IdentityUser>(TimeSpan.Zero).Invoke(context);
            Assert.Null(context.Identity);
            signInManager.VerifyAll();
        }
开发者ID:ChMar,项目名称:Identity,代码行数:26,代码来源:SecurityStampValidatorTest.cs

示例2: Can_use_connection_string_name_in_OnConfiguring_test

        private async Task Can_use_connection_string_name_in_OnConfiguring_test(string connectionName)
        {
            var configuration = new Configuration
                {
                    new MemoryConfigurationSource(
                        new Dictionary<string, string>
                            {
                                { "Data:Northwind:ConnectionString", SqlServerTestDatabase.NorthwindConnectionString }
                            })
                };

            var serviceCollection = new ServiceCollection();
            serviceCollection
                .AddInstance<IConfiguration>(configuration)
                .AddEntityFramework()
                .AddSqlServer();

            var serviceProvider = serviceCollection.BuildServiceProvider();

            using (await SqlServerTestDatabase.Northwind())
            {
                using (var context = new NorthwindContext(serviceProvider, connectionName))
                {
                    Assert.Equal(91, await context.Customers.CountAsync());
                }
            }
        }
开发者ID:Nyaoso,项目名称:EntityFramework,代码行数:27,代码来源:ConnectionStringTest.cs

示例3: AddWebEncoders_DoesNotOverrideExistingRegisteredEncoders

        public void AddWebEncoders_DoesNotOverrideExistingRegisteredEncoders()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();

            // Act
            serviceCollection.AddSingleton<IHtmlEncoder, CommonTestEncoder>();
            serviceCollection.AddSingleton<IJavaScriptStringEncoder, CommonTestEncoder>();
            // we don't register an existing URL encoder
            serviceCollection.AddWebEncoders(options =>
            {
                options.CodePointFilter = new CodePointFilter().AllowChars("ace"); // only these three chars are allowed
            });

            // Assert
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var htmlEncoder = serviceProvider.GetHtmlEncoder();
            Assert.Equal("HtmlEncode[[abcde]]", htmlEncoder.HtmlEncode("abcde"));

            var javaScriptStringEncoder = serviceProvider.GetJavaScriptStringEncoder();
            Assert.Equal("JavaScriptStringEncode[[abcde]]", javaScriptStringEncoder.JavaScriptStringEncode("abcde"));

            var urlEncoder = serviceProvider.GetUrlEncoder();
            Assert.Equal("a%62c%64e", urlEncoder.UrlEncode("abcde"));
        }
开发者ID:EgoDust,项目名称:HttpAbstractions,代码行数:26,代码来源:EncoderServiceCollectionExtensionsTests.cs

示例4: AddWebEncoders_WithOptions_RegistersEncodersWithCustomCodeFilter

        public void AddWebEncoders_WithOptions_RegistersEncodersWithCustomCodeFilter()
        {
            // Arrange
            var serviceCollection = new ServiceCollection();

            // Act
            serviceCollection.AddWebEncoders(options =>
            {
                options.CodePointFilter = new CodePointFilter().AllowChars("ace"); // only these three chars are allowed
            });

            // Assert
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var htmlEncoder = serviceProvider.GetRequiredService<IHtmlEncoder>();
            Assert.Equal("a&#x62;c&#x64;e", htmlEncoder.HtmlEncode("abcde"));
            Assert.Same(htmlEncoder, serviceProvider.GetRequiredService<IHtmlEncoder>()); // as singleton instance

            var javaScriptStringEncoder = serviceProvider.GetRequiredService<IJavaScriptStringEncoder>();
            Assert.Equal(@"a\u0062c\u0064e", javaScriptStringEncoder.JavaScriptStringEncode("abcde"));
            Assert.Same(javaScriptStringEncoder, serviceProvider.GetRequiredService<IJavaScriptStringEncoder>()); // as singleton instance

            var urlEncoder = serviceProvider.GetRequiredService<IUrlEncoder>();
            Assert.Equal("a%62c%64e", urlEncoder.UrlEncode("abcde"));
            Assert.Same(urlEncoder, serviceProvider.GetRequiredService<IUrlEncoder>()); // as singleton instance
        }
开发者ID:EgoDust,项目名称:HttpAbstractions,代码行数:26,代码来源:EncoderServiceCollectionExtensionsTests.cs

示例5: Activate_InitializesTagHelpersWithMultipleInitializers

        public void Activate_InitializesTagHelpersWithMultipleInitializers()
        {
            // Arrange
            var services = new ServiceCollection();
            services.InitializeTagHelper<TestTagHelper>((h, vc) =>
            {
                h.Name = "Test 1";
                h.Number = 100;
            });
            services.InitializeTagHelper<TestTagHelper>((h, vc) =>
            {
                h.Name += ", Test 2";
                h.Number += 100;
            });
            var httpContext = MakeHttpContext(services.BuildServiceProvider());
            var viewContext = MakeViewContext(httpContext);
            var activator = new DefaultTagHelperActivator();
            var helper = new TestTagHelper();

            // Act
            activator.Activate(helper, viewContext);

            // Assert
            Assert.Equal("Test 1, Test 2", helper.Name);
            Assert.Equal(200, helper.Number);
        }
开发者ID:RehanSaeed,项目名称:Mvc,代码行数:26,代码来源:DefaultTagHelperActivatorTest.cs

示例6: Main

        public void Main(string[] args)
        {
            var services = new ServiceCollection();

            services
                .AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<UserDbContext>()
                .AddEntityFrameworkMixins();

            var provider = services.BuildServiceProvider();
            var context = provider.GetRequiredService<UserDbContext>();

            var users = (
                from u in context.Users
                where u.Mixin<Author>().GooglePlusProfile != null
                select u //u.Mixin<Author>()
            ).ToList();

            var user = users.FirstOrDefault();
            if (user != null)
            {
                var author = user.Mixin<Author>();

                // You can make changes here:
                author.IsAwesome = true;

                // Save changes
                context.SaveChanges();
            }
        }
开发者ID:Antaris,项目名称:EntityFrameworkMixins,代码行数:31,代码来源:Program.cs

示例7: CanIncludeUserClaimsTest

        public async Task CanIncludeUserClaimsTest()
        {
            // Arrange
            CreateContext(true);
            var builder = new ApplicationBuilder(CallContextServiceLocator.Locator.ServiceProvider);

            var services = new ServiceCollection();
            DbUtil.ConfigureDbServices<IdentityDbContext>(ConnectionString, services);
            services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<IdentityDbContext>();
            builder.ApplicationServices = services.BuildServiceProvider();

            var userManager = builder.ApplicationServices.GetRequiredService<UserManager<IdentityUser>>();
            var dbContext = builder.ApplicationServices.GetRequiredService<IdentityDbContext>();

            var username = "user" + new Random().Next();
            var user = new IdentityUser() { UserName = username };
            IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user));

            for (var i = 0; i < 10; i++)
            {
                IdentityResultAssert.IsSuccess(await userManager.AddClaimAsync(user, new Claim(i.ToString(), "foo")));
            }

            user = dbContext.Users.Include(x => x.Claims).FirstOrDefault(x => x.UserName == username);

            // Assert
            Assert.NotNull(user);
            Assert.NotNull(user.Claims);
            Assert.Equal(10, user.Claims.Count());
        }
开发者ID:stormwild,项目名称:Identity,代码行数:30,代码来源:DefaultPocoTest.cs

示例8: ClientRulesWithCompareAttribute_ErrorMessageUsesDisplayName

        public void ClientRulesWithCompareAttribute_ErrorMessageUsesDisplayName()
        {
            // Arrange
            var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = metadataProvider.GetMetadataForProperty(typeof(PropertyDisplayNameModel), "MyProperty");

            var attribute = new CompareAttribute("OtherProperty");
            var adapter = new CompareAttributeAdapter(attribute);

            var serviceCollection = new ServiceCollection();
            var requestServices = serviceCollection.BuildServiceProvider();

            var context = new ClientModelValidationContext(metadata, metadataProvider, requestServices);

            // Act
            var rules = adapter.GetClientValidationRules(context);

            // Assert
            var rule = Assert.Single(rules);
            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(
                PlatformNormalizer.NormalizeContent(
                    "'MyPropertyDisplayName' and 'OtherPropertyDisplayName' do not match."),
                rule.ErrorMessage);
        }
开发者ID:notami18,项目名称:Mvc,代码行数:25,代码来源:CompareAttributeAdapterTest.cs

示例9: json_collection_with_default_culture_test

        public void json_collection_with_default_culture_test()
        {
            // Arrange
            var req = new Mock<HttpRequest>();
            req.Setup(x => x.Headers)
                .Returns(new HeaderDictionary(new Dictionary<string, StringValues> { }));
            req.Setup(x => x.Cookies)
                .Returns(new RequestCookiesCollection());
            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(x => x.Request)
                .Returns(req.Object);
            var accessor = new Mock<IHttpContextAccessor>();
            accessor.Setup(x => x.HttpContext)
                .Returns(httpContext.Object);

            var collection = new ServiceCollection();
            collection.AddJsonLocalization()
                .AddCookieCulture()
                .AddInstance(accessor.Object)
                .AddInstance(CallContextServiceLocator.Locator.ServiceProvider.GetRequiredService<IApplicationEnvironment>());

            var service = collection.BuildServiceProvider();

            // Act
            var SR = service.GetService<ILocalizationStringCollection>();
            var actual_1 = SR["Hello world."];
            var actual_2 = SR["My name is {0}.", "Yuuko"];

            // Assert
            Assert.Equal("你好,世界。", actual_1);
            Assert.Equal("我的名字是Yuuko", actual_2);
        }
开发者ID:CodeComb,项目名称:Localization,代码行数:32,代码来源:JsonCollectionTests.cs

示例10: Main

        public Task<int> Main(string[] args)
        {
            //Add command line configuration source to read command line parameters.
            var config = new Configuration();
            config.AddCommandLine(args);

            var serviceCollection = new ServiceCollection();
            serviceCollection.Add(HostingServices.GetDefaultServices(config));
            var services = serviceCollection.BuildServiceProvider(_hostServiceProvider);

            var context = new HostingContext()
            {
                Services = services,
                Configuration = config,
                ServerName = "Microsoft.AspNet.Server.WebListener",
                ApplicationName = "BugTracker"
            };

            var engine = services.GetService<IHostingEngine>();
            if (engine == null)
            {
                throw new Exception("TODO: IHostingEngine service not available exception");
            }

            using (engine.Start(context))
            {
                Console.WriteLine("Started the server..");
                Console.WriteLine("Press any key to stop the server");
                Console.ReadLine();
            }
            return Task.FromResult(0);
        }
开发者ID:jack4it,项目名称:BugTracker,代码行数:32,代码来源:Program.cs

示例11: GetKeyEscrowSink_MultipleKeyEscrowRegistration_ReturnsAggregate

        public void GetKeyEscrowSink_MultipleKeyEscrowRegistration_ReturnsAggregate()
        {
            // Arrange
            List<string> output = new List<string>();

            var mockKeyEscrowSink1 = new Mock<IKeyEscrowSink>();
            mockKeyEscrowSink1.Setup(o => o.Store(It.IsAny<Guid>(), It.IsAny<XElement>()))
                .Callback<Guid, XElement>((keyId, element) =>
                {
                    output.Add(String.Format(CultureInfo.InvariantCulture, "[sink1] {0:D}: {1}", keyId, element.Name.LocalName));
                });

            var mockKeyEscrowSink2 = new Mock<IKeyEscrowSink>();
            mockKeyEscrowSink2.Setup(o => o.Store(It.IsAny<Guid>(), It.IsAny<XElement>()))
                .Callback<Guid, XElement>((keyId, element) =>
                {
                    output.Add(String.Format(CultureInfo.InvariantCulture, "[sink2] {0:D}: {1}", keyId, element.Name.LocalName));
                });

            var serviceCollection = new ServiceCollection();
            serviceCollection.AddInstance<IKeyEscrowSink>(mockKeyEscrowSink1.Object);
            serviceCollection.AddInstance<IKeyEscrowSink>(mockKeyEscrowSink2.Object);
            var services = serviceCollection.BuildServiceProvider();

            // Act
            var sink = services.GetKeyEscrowSink();
            sink.Store(new Guid("39974d8e-3e53-4d78-b7e9-4ff64a2a5d7b"), XElement.Parse("<theElement />"));

            // Assert
            Assert.Equal(new[] { "[sink1] 39974d8e-3e53-4d78-b7e9-4ff64a2a5d7b: theElement", "[sink2] 39974d8e-3e53-4d78-b7e9-4ff64a2a5d7b: theElement" }, output);
        }
开发者ID:hishamco,项目名称:DataProtection,代码行数:31,代码来源:KeyEscrowServiceProviderExtensionsTests.cs

示例12: OnValidatePrincipalTestSuccess

        public async Task OnValidatePrincipalTestSuccess(bool isPersistent)
        {
            var user = new TestUser("test");
            var userManager = MockHelpers.MockUserManager<TestUser>();
            var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>();
            var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.Zero };
            var options = new Mock<IOptions<IdentityOptions>>();
            options.Setup(a => a.Options).Returns(identityOptions);
            var httpContext = new Mock<HttpContext>();
            var contextAccessor = new Mock<IHttpContextAccessor>();
            contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
            var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object,
                contextAccessor.Object, claimsManager.Object, options.Object, null);
            signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).ReturnsAsync(user).Verifiable();
            signInManager.Setup(s => s.SignInAsync(user, isPersistent, null)).Returns(Task.FromResult(0)).Verifiable();
            var services = new ServiceCollection();
            services.AddInstance(options.Object);
            services.AddInstance(signInManager.Object);
            services.AddInstance<ISecurityStampValidator>(new SecurityStampValidator<TestUser>());
            httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
            var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationScheme);
            id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

            var ticket = new AuthenticationTicket(new ClaimsPrincipal(id), 
                new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow, IsPersistent = isPersistent }, 
                IdentityOptions.ApplicationCookieAuthenticationScheme);
            var context = new CookieValidatePrincipalContext(httpContext.Object, ticket, new CookieAuthenticationOptions());
            Assert.NotNull(context.Properties);
            Assert.NotNull(context.Options);
            Assert.NotNull(context.Principal);
            await
                SecurityStampValidator.ValidatePrincipalAsync(context);
            Assert.NotNull(context.Principal);
            signInManager.VerifyAll();
        }
开发者ID:stormwild,项目名称:Identity,代码行数:35,代码来源:SecurityStampValidatorTest.cs

示例13: BuildServiceProvider

        // Composition root
        private IServiceProvider BuildServiceProvider(Options options, IConfigurationSection queueConfig)
        {
            var services = new ServiceCollection().AddLogging();

            services.AddSingleton<IMessageHandlerFactory, MessageHandlerFactory>();

            switch (options.QueueType)
            {
                case "zeromq":
                    services.AddZeroMq(queueConfig);
                    break;
                case "msmq":
                    services.AddMsmq(queueConfig);
                    break;
                case "azure":
                    services.AddAzure(queueConfig);
                    break;
                default:
                    throw new Exception($"Could not resolve queue type {options.QueueType}");
            }

            if (!string.IsNullOrWhiteSpace(options.Handler))
            {
                services.AddTransient(typeof(IMessageHandler), Type.GetType(options.Handler));
            }

            var provider = services.BuildServiceProvider();

            // configure
            var loggerFactory = provider.GetRequiredService<ILoggerFactory>();
            loggerFactory.MinimumLevel = LogLevel.Debug;
            loggerFactory.AddConsole(loggerFactory.MinimumLevel);

            return provider;
        }
开发者ID:Kieranties,项目名称:MessagingPlayground,代码行数:36,代码来源:Program.cs

示例14: Main

        public void Main(string[] args) {
            var connectionString = @"Data Source=(localdb)\mssqllocaldb;Initial Catalog=Test;Integrated Security=True;Connect Timeout=30;";
            IServiceCollection services = new ServiceCollection();
            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<DataContext>(options => options.UseSqlServer(connectionString));

            var serviceProvider = services.BuildServiceProvider();
            //serviceProvider.Add
            
            var context = serviceProvider.GetService<DataContext>();

            var categoryCount = context.Categories.Count();
            Console.WriteLine($"category count is {categoryCount}");

            var newCat = new Category {
                Name = $"Category {categoryCount + 1}",
                Description = $"Category {categoryCount + 1} description"
            };
            context.Add(newCat);
            //context.SaveChanges();
            var count = context.SaveChanges();
            Console.WriteLine($"change count is {count}");
            context.Dispose();
            Console.WriteLine("Hello, world!");
        }
开发者ID:beginor,项目名称:practice,代码行数:26,代码来源:Program.cs

示例15: CreateRoleManager

 public static RoleManager<IdentityRole> CreateRoleManager(InMemoryContext context)
 {
     var services = new ServiceCollection();
     services.AddIdentity<IdentityUser, IdentityRole>();
     services.AddInstance<IRoleStore<IdentityRole>>(new RoleStore<IdentityRole>(context));
     return services.BuildServiceProvider().GetRequiredService<RoleManager<IdentityRole>>();
 }
开发者ID:stormwild,项目名称:Identity,代码行数:7,代码来源:TestIdentityFactory.cs


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