• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# ServiceCollection类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中ServiceCollection的典型用法代码示例。如果您正苦于以下问题:C# ServiceCollection类的具体用法?C# ServiceCollection怎么用?C# ServiceCollection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: ConfigureConfigServerClientSettingsOptions_WithDefaults

        public void ConfigureConfigServerClientSettingsOptions_WithDefaults()
        {
            // Arrange
            var services = new ServiceCollection().AddOptions();
            var environment = new HostingEnvironment();

            // Act and Assert
            var builder = new ConfigurationBuilder().AddConfigServer(environment);
            var config = builder.Build();

            services.Configure<ConfigServerClientSettingsOptions>(config);
            var service = services.BuildServiceProvider().GetService<IOptions<ConfigServerClientSettingsOptions>>();
            Assert.NotNull(service);
            var options = service.Value;
            Assert.NotNull(options);
            ConfigServerTestHelpers.VerifyDefaults(options.Settings);

            Assert.Equal(ConfigServerClientSettings.DEFAULT_PROVIDER_ENABLED, options.Enabled);
            Assert.Equal(ConfigServerClientSettings.DEFAULT_FAILFAST, options.FailFast);
            Assert.Equal(ConfigServerClientSettings.DEFAULT_URI, options.Uri);
            Assert.Equal(ConfigServerClientSettings.DEFAULT_ENVIRONMENT, options.Environment);
            Assert.Equal(ConfigServerClientSettings.DEFAULT_CERTIFICATE_VALIDATION, options.ValidateCertificates);
            Assert.Null(options.Name);
            Assert.Null(options.Label);
            Assert.Null(options.Username);
            Assert.Null(options.Password);
        }
开发者ID:sdougherty,项目名称:Configuration,代码行数:27,代码来源:ConfigServerClientSettingsOptionsTest.cs


示例2: SaveChanges_delegates

        public void SaveChanges_delegates()
        {
            var commandBatchPreparerMock = new Mock<ICommandBatchPreparer>();
            var batchExecutorMock = new Mock<IBatchExecutor>();
            var relationalConnectionMock = new Mock<IRelationalConnection>();

            var fragmentTranslatorMock = new Mock<IExpressionFragmentTranslator>();

            var customServices = new ServiceCollection()
                .AddInstance(commandBatchPreparerMock.Object)
                .AddInstance(batchExecutorMock.Object)
                .AddInstance(relationalConnectionMock.Object)
                .AddInstance(fragmentTranslatorMock.Object)
                .AddScoped<RelationalDatabase>();

            var contextServices = RelationalTestHelpers.Instance.CreateContextServices(customServices);

            var relationalDatabase = contextServices.GetRequiredService<RelationalDatabase>();

            var entries = new List<InternalEntityEntry>();

            relationalDatabase.SaveChanges(entries);

            commandBatchPreparerMock.Verify(c => c.BatchCommands(entries));
            batchExecutorMock.Verify(be => be.Execute(It.IsAny<IEnumerable<ModificationCommandBatch>>(), relationalConnectionMock.Object));
        }
开发者ID:adwardliu,项目名称:EntityFramework,代码行数:26,代码来源:RelationalDatabaseTest.cs


示例3: MultiRegistrationServiceTypes_AreRegistered_MultipleTimes

        public void MultiRegistrationServiceTypes_AreRegistered_MultipleTimes()
        {
            // Arrange
            var services = new ServiceCollection();

            // Register a mock implementation of each service, AddMvcServices should add another implemenetation.
            foreach (var serviceType in MutliRegistrationServiceTypes)
            {
                var mockType = typeof(Mock<>).MakeGenericType(serviceType.Key);
                services.Add(ServiceDescriptor.Transient(serviceType.Key, mockType));
            }

            // Act
            MvcCoreServiceCollectionExtensions.AddMvcCoreServices(services);

            // Assert
            foreach (var serviceType in MutliRegistrationServiceTypes)
            {
                AssertServiceCountEquals(services, serviceType.Key, serviceType.Value.Length + 1);

                foreach (var implementationType in serviceType.Value)
                {
                    AssertContainsSingle(services, serviceType.Key, implementationType);
                }
            }
        }
开发者ID:phinq19,项目名称:git_example,代码行数:26,代码来源:MvcCoreServiceCollectionExtensionsTest.cs


示例4: Can_use_explicit_values

        public async Task Can_use_explicit_values()
        {
            var serviceProvider = new ServiceCollection()
                .AddEntityFrameworkSqlServer()
                .BuildServiceProvider();

            var guids = new List<Guid>();

            using (var context = new BronieContext(serviceProvider, "GooieExplicitBronies"))
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();

                for (var i = 0; i < 50; i++)
                {
                    guids.Add(context.Add(new Pegasus { Name = "Rainbow Dash " + i, Index = i, Id = Guid.NewGuid() }).Entity.Id);
                }

                await context.SaveChangesAsync();
            }

            using (var context = new BronieContext(serviceProvider, "GooieExplicitBronies"))
            {
                var pegasuses = await context.Pegasuses.OrderBy(e => e.Index).ToListAsync();

                for (var i = 0; i < 50; i++)
                {
                    Assert.Equal("Rainbow Dash " + i, pegasuses[i].Name);
                    Assert.Equal(guids[i], pegasuses[i].Id);
                }
            }
        }
开发者ID:RickyLin,项目名称:EntityFramework,代码行数:32,代码来源:SequentialGuidEndToEndTest.cs


示例5: 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.AddSingleton<IKeyEscrowSink>(mockKeyEscrowSink1.Object);
            serviceCollection.AddSingleton<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:yonglehou,项目名称:DataProtection,代码行数:31,代码来源:KeyEscrowServiceProviderExtensionsTests.cs


示例6: Initializes_all_entity_set_properties_with_setters

        public void Initializes_all_entity_set_properties_with_setters()
        {
            var setterFactory = new ClrPropertySetterFactory();

            var setFinderMock = new Mock<IDbSetFinder>();
            setFinderMock.Setup(m => m.FindSets(It.IsAny<DbContext>())).Returns(
                new[]
                {
                    new DbSetProperty("One", typeof(string), setterFactory.Create(typeof(JustAContext).GetAnyProperty("One"))),
                    new DbSetProperty("Two", typeof(object), setterFactory.Create(typeof(JustAContext).GetAnyProperty("Two"))),
                    new DbSetProperty("Three", typeof(string), setterFactory.Create(typeof(JustAContext).GetAnyProperty("Three"))),
                    new DbSetProperty("Four", typeof(string), null)
                });

            var customServices = new ServiceCollection()
                .AddInstance<IDbSetInitializer>(new DbSetInitializer(setFinderMock.Object, new DbSetSource()));

            var serviceProvider = TestHelpers.Instance.CreateServiceProvider(customServices);

            using (var context = new JustAContext(serviceProvider, new DbContextOptionsBuilder().Options))
            {
                Assert.NotNull(context.One);
                Assert.NotNull(context.GetTwo());
                Assert.NotNull(context.Three);
                Assert.Null(context.Four);
            }
        }
开发者ID:adwardliu,项目名称:EntityFramework,代码行数:27,代码来源:DbSetInitializerTest.cs


示例7: ClientRulesWithMaxLengthAttribute_StringLocalizer_ReturnsLocalizedErrorString

        public void ClientRulesWithMaxLengthAttribute_StringLocalizer_ReturnsLocalizedErrorString()
        {
            // Arrange
            var provider = TestModelMetadataProvider.CreateDefaultProvider();
            var metadata = provider.GetMetadataForProperty(typeof(string), "Length");
            var errorKey = metadata.GetDisplayName();
            var attribute = new MaxLengthAttribute(10);
            attribute.ErrorMessage = errorKey;

            var localizedString = new LocalizedString(errorKey, "Longueur est invalide");
            var stringLocalizer = new Mock<IStringLocalizer>();
            stringLocalizer.Setup(s => s[errorKey]).Returns(localizedString);

            var adapter = new MaxLengthAttributeAdapter(attribute, stringLocalizer.Object);
            var serviceCollection = new ServiceCollection();
            var requestServices = serviceCollection.BuildServiceProvider();
            var context = new ClientModelValidationContext(metadata, provider, requestServices);

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

            // Assert
            var rule = Assert.Single(rules);
            Assert.Equal("maxlength", rule.ValidationType);
            Assert.Equal(1, rule.ValidationParameters.Count);
            Assert.Equal(10, rule.ValidationParameters["max"]);
            Assert.Equal("Longueur est invalide", rule.ErrorMessage);
        }
开发者ID:huoxudong125,项目名称:Mvc,代码行数:28,代码来源:MaxLengthAttributeAdapterTest.cs


示例8: ResolvedServiceGetResponseEncoder

        public void ResolvedServiceGetResponseEncoder()
        {
            ServiceCollection services = new ServiceCollection();
            services
                .WithService("Test", "/")
                    .WithEndpoint("{action}")
                        .Post<Payload>((Payload p) => { });

            ResolvedService service = new ServiceResolver(services).Find(MethodType.Post, "foo");
            EncodingLookupResult result = service.GetResponseEncoder("gzip");
            Assert.IsNotNull(result);
            Assert.AreEqual(EncodingType.Empty, result.EncodingType);
            Assert.AreEqual(new IdentityEncoding(), result.Encoding);

            result = service.GetResponseEncoder("gzip, *");
            Assert.IsNotNull(result);
            Assert.AreEqual(EncodingType.Empty, result.EncodingType);
            Assert.AreEqual(new IdentityEncoding(), result.Encoding);

            services.WithHostEncoding(new GzipDeflateEncoding());
            service = new ServiceResolver(services).Find(MethodType.Post, "foo");
            result = service.GetResponseEncoder("gzip, *");
            Assert.IsNotNull(result);
            Assert.AreEqual(EncodingType.Parse("gzip"), result.EncodingType);
            Assert.AreEqual(new GzipDeflateEncoding(), result.Encoding);

            result = service.GetResponseEncoder("gzip;q=0");
            Assert.IsNotNull(result);
            Assert.AreEqual(EncodingType.Empty, result.EncodingType);
            Assert.AreEqual(new IdentityEncoding(), result.Encoding);
        }
开发者ID:ChadBurggraf,项目名称:small-fry,代码行数:31,代码来源:ResolvedServiceTests.cs


示例9: Main

        public static void Main(string[] args)
        {
            // serilog provider configuration
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.ColoredConsole()
                .CreateLogger();

            // logger factory for program.cs - startup case
            var log = new LoggerFactory().AddSerilog().CreateLogger(typeof(Program).FullName);
            log.LogInformation("Starting from console launcher... press enter to stop.");

            // load config
            var config = new ConfigurationBuilder()
                            .AddJsonFile("analyserconf.json")
                            .Build();

            // use microsofts built in simple DI container.
            var services = new ServiceCollection();
            configureServices(services, config);
            var sp = services.BuildServiceProvider();

            IDictionary<uint, AircraftBeaconSpeedAndTrack> beaconDisplayBuffer = null;
            var events = new Dictionary<string, List<AircraftTrackEvent>>();

            // disposable pattern to stop on read-line.
            using (var analyser = sp.GetService<Core.OGNAnalyser>())
            {
                attachConsoleDisplay(beaconDisplayBuffer, events, analyser);
                Console.ReadLine();
            }
        }
开发者ID:sgacond,项目名称:OGNAnalyser,代码行数:32,代码来源:Program.cs


示例10: ExpandViewLocations_SpecificPlugin

        public void ExpandViewLocations_SpecificPlugin(
            string pluginName, 
            bool exists,
            IEnumerable<string> viewLocations,
            IEnumerable<string> expectedViewLocations)
        {
            var pluginManagerMock = new Mock<IPluginManager>();
            if(exists)
                pluginManagerMock.Setup(pm => pm[It.IsAny<TypeInfo>()])
                    .Returns(new PluginInfo(new ModuleStub { UrlPrefix = pluginName }, null, null, null));;

            var services = new ServiceCollection();
            services.Add(new ServiceDescriptor(typeof(IPluginManager), pluginManagerMock.Object));

            var target = new PluginViewLocationExtender();
            var actionContext = new ActionContext { HttpContext = new DefaultHttpContext { RequestServices = services.BuildServiceProvider() } };
            actionContext.ActionDescriptor = new ControllerActionDescriptor { ControllerTypeInfo = typeof(object).GetTypeInfo() };
            var context = new ViewLocationExpanderContext(
               actionContext,
               "testView",
               "test-controller",
               "",
               false);

            var result = target.ExpandViewLocations(context, viewLocations);

            Assert.Equal(expectedViewLocations, result);
        }
开发者ID:genusP,项目名称:AspNet5-Modularity,代码行数:28,代码来源:PluginViewLocationExtenderTests.cs


示例11: 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:TwoToneBytes,项目名称:HttpAbstractions,代码行数:26,代码来源:EncoderServiceCollectionExtensionsTests.cs


示例12: 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:TwoToneBytes,项目名称:HttpAbstractions,代码行数:26,代码来源:EncoderServiceCollectionExtensionsTests.cs


示例13: ConfigureStartup

        internal static IServiceProvider ConfigureStartup(string startupTypeName, Action<IServiceCollection, bool> registerSystemTypes)
        {
            var usingCustomServiceProvider = false;
            IServiceCollection serviceCollection = new ServiceCollection();
            ConfigureServicesBuilder servicesMethod = null;
            Type startupType = null;

            if (!string.IsNullOrWhiteSpace(startupTypeName))
            {
                startupType = Type.GetType(startupTypeName);
                if (startupType == null)
                {
                    throw new InvalidOperationException($"Can not locate the type specified in the configuration file: '{startupTypeName}'.");
                }

                servicesMethod = FindConfigureServicesDelegate(startupType);
                if (servicesMethod != null && !servicesMethod.MethodInfo.IsStatic)
                {
                    usingCustomServiceProvider = true;
                }
            }

            registerSystemTypes(serviceCollection, usingCustomServiceProvider);

            if (usingCustomServiceProvider)
            {
                var instance = Activator.CreateInstance(startupType);
                return servicesMethod.Build(instance, serviceCollection);
            }

            return serviceCollection.BuildServiceProvider();
        }
开发者ID:jdom,项目名称:orleans,代码行数:32,代码来源:StartupBuilder.cs


示例14: FetchAll

 public ServiceCollection FetchAll()
 {
     ServiceCollection coll = new ServiceCollection();
     Query qry = new Query(Service.Schema);
     coll.LoadAndCloseReader(qry.ExecuteReader());
     return coll;
 }
开发者ID:zaheerahmad,项目名称:Admin,代码行数:7,代码来源:ServiceController.cs


示例15: CreateNewKey_CallsInternalManager

        public void CreateNewKey_CallsInternalManager()
        {
            // Arrange - mocks
            DateTimeOffset minCreationDate = DateTimeOffset.UtcNow;
            DateTimeOffset? actualCreationDate = null;
            DateTimeOffset activationDate = minCreationDate + TimeSpan.FromDays(7);
            DateTimeOffset expirationDate = activationDate.AddMonths(1);
            var mockInternalKeyManager = new Mock<IInternalXmlKeyManager>();
            mockInternalKeyManager
                .Setup(o => o.CreateNewKey(It.IsAny<Guid>(), It.IsAny<DateTimeOffset>(), activationDate, expirationDate))
                .Callback<Guid, DateTimeOffset, DateTimeOffset, DateTimeOffset>((innerKeyId, innerCreationDate, innerActivationDate, innerExpirationDate) =>
                {
                    actualCreationDate = innerCreationDate;
                });

            // Arrange - services
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddSingleton<IXmlRepository>(new Mock<IXmlRepository>().Object);
            serviceCollection.AddSingleton<IAuthenticatedEncryptorConfiguration>(new Mock<IAuthenticatedEncryptorConfiguration>().Object);
            serviceCollection.AddSingleton<IInternalXmlKeyManager>(mockInternalKeyManager.Object);
            var services = serviceCollection.BuildServiceProvider();
            var keyManager = new XmlKeyManager(services);

            // Act
            keyManager.CreateNewKey(activationDate, expirationDate);

            // Assert
            Assert.InRange(actualCreationDate.Value, minCreationDate, DateTimeOffset.UtcNow);
        }
开发者ID:yonglehou,项目名称:DataProtection,代码行数:29,代码来源:XmlKeyManagerTests.cs


示例16: Can_use_sequence_end_to_end_async

        public async Task Can_use_sequence_end_to_end_async()
        {
            var serviceProvider = new ServiceCollection()
                .AddEntityFrameworkSqlServer()
                .BuildServiceProvider();

            using (var context = new BronieContext(serviceProvider, "BroniesAsync"))
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();
            }

            await AddEntitiesAsync(serviceProvider, "BroniesAsync");
            await AddEntitiesAsync(serviceProvider, "BroniesAsync");

            // Use a different service provider so a different generator is used but with
            // the same server sequence.
            serviceProvider = new ServiceCollection()
                .AddEntityFrameworkSqlServer()
                .BuildServiceProvider();

            await AddEntitiesAsync(serviceProvider, "BroniesAsync");

            using (var context = new BronieContext(serviceProvider, "BroniesAsync"))
            {
                var pegasuses = await context.Pegasuses.ToListAsync();

                for (var i = 0; i < 10; i++)
                {
                    Assert.Equal(3, pegasuses.Count(p => p.Name == "Rainbow Dash " + i));
                    Assert.Equal(3, pegasuses.Count(p => p.Name == "Fluttershy " + i));
                }
            }
        }
开发者ID:ChuYuzhi,项目名称:EntityFramework,代码行数:34,代码来源:SequenceEndToEndTest.cs


示例17: CreateChildContainer

        /// <summary>
        /// Creates a child container.
        /// </summary>
        /// <param name="serviceProvider">The service provider to create a child container for.</param>
        /// <param name="serviceCollection">The services to clone.</param>
        public static IServiceCollection CreateChildContainer(this IServiceProvider serviceProvider, IServiceCollection serviceCollection)
        {
            IServiceCollection clonedCollection = new ServiceCollection();

            foreach (var service in serviceCollection) {
                // Register the singleton instances to all containers
                if (service.Lifetime == ServiceLifetime.Singleton) {
                    var serviceTypeInfo = service.ServiceType.GetTypeInfo();

                    // Treat open-generic registrations differently
                    if (serviceTypeInfo.IsGenericType && serviceTypeInfo.GenericTypeArguments.Length == 0) {
                        // There is no Func based way to register an open-generic type, instead of
                        // tenantServiceCollection.AddSingleton(typeof(IEnumerable<>), typeof(List<>));
                        // Right now, we regsiter them as singleton per cloned scope even though it's wrong
                        // but in the actual examples it won't matter.
                        clonedCollection.AddSingleton(service.ServiceType, service.ImplementationType);
                    }
                    else {
                        // When a service from the main container is resolved, just add its instance to the container.
                        // It will be shared by all tenant service providers.
                        clonedCollection.AddInstance(service.ServiceType, serviceProvider.GetService(service.ServiceType));
                    }
                }
                else {
                    clonedCollection.Add(service);
                }
            }

            return clonedCollection;
        }
开发者ID:SmartFire,项目名称:Orchard2,代码行数:35,代码来源:ServiceProviderExtensions.cs


示例18: 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, stringLocalizer: null);

            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:huoxudong125,项目名称:Mvc,代码行数:25,代码来源:CompareAttributeAdapterTest.cs


示例19: Can_use_GUIDs_end_to_end_async

        public async Task Can_use_GUIDs_end_to_end_async()
        {
            var serviceProvider = new ServiceCollection()
                .AddEntityFrameworkInMemoryDatabase()
                .BuildServiceProvider();

            var guids = new List<Guid>();
            var guidsHash = new HashSet<Guid>();
            using (var context = new BronieContext(serviceProvider))
            {
                for (var i = 0; i < 10; i++)
                {
                    guids.Add(context.Add(new Pegasus { Name = "Rainbow Dash " + i }).Entity.Id);
                    guidsHash.Add(guids.Last());
                }

                await context.SaveChangesAsync();
            }

            Assert.Equal(10, guidsHash.Count);

            using (var context = new BronieContext(serviceProvider))
            {
                var pegasuses = await context.Pegasuses.OrderBy(e => e.Name).ToListAsync();

                for (var i = 0; i < 10; i++)
                {
                    Assert.Equal(guids[i], pegasuses[i].Id);
                }
            }
        }
开发者ID:RickyLin,项目名称:EntityFramework,代码行数:31,代码来源:GuidValueGeneratorEndToEndTest.cs


示例20: ConfigurationRegistersHookPointsCorrectly

        public void ConfigurationRegistersHookPointsCorrectly()
        {
            IServiceCollection services = new ServiceCollection();
            var configuration = services.BuildApiConfiguration();

            Assert.Null(configuration.GetApiService<IHookA>());
            Assert.Null(configuration.GetApiService<IHookB>());

            var singletonHookPoint = new HookA();
            services.CutoffPrevious<IHookA>(singletonHookPoint);
            configuration = services.BuildApiConfiguration();
            Assert.Same(singletonHookPoint, configuration.GetApiService<IHookA>());
            Assert.Null(configuration.GetApiService<IHookB>());

            var multiCastHookPoint1 = new HookB();
            services.CutoffPrevious<IHookB>(multiCastHookPoint1);
            configuration = services.BuildApiConfiguration();
            Assert.Same(singletonHookPoint, configuration.GetApiService<IHookA>());
            Assert.Equal(multiCastHookPoint1, configuration.GetApiService<IHookB>());

            services = new ServiceCollection()
                .CutoffPrevious<IHookB>(multiCastHookPoint1)
                .ChainPrevious<IHookB, HookB>()
                .AddInstance(new HookB());
            configuration = services.BuildApiConfiguration();
            var multiCastHookPoint2 = configuration.GetApiService<HookB>();
            var handler = configuration.GetApiService<IHookB>();
            Assert.Equal(multiCastHookPoint2, handler);

            var delegateHandler = handler as HookB;
            Assert.NotNull(delegateHandler);
            Assert.Equal(multiCastHookPoint1, delegateHandler.InnerHandler);
        }
开发者ID:kosinsky,项目名称:RESTier,代码行数:33,代码来源:ApiConfiguration.Tests.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# ServiceContainer类代码示例发布时间:2022-05-24
下一篇:
C# ServiceClient类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap