本文整理汇总了C#中ServiceCollection类的典型用法代码示例。如果您正苦于以下问题:C# ServiceCollection类的具体用法?C# ServiceCollection怎么用?C# ServiceCollection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ServiceCollection类属于命名空间,在下文中一共展示了ServiceCollection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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);
}
示例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));
}
示例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);
}
}
}
示例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);
}
}
}
示例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);
}
示例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);
}
}
示例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);
}
示例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);
}
示例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();
}
}
示例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);
}
示例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"));
}
示例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("abcde", 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
}
示例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();
}
示例14: FetchAll
public ServiceCollection FetchAll()
{
ServiceCollection coll = new ServiceCollection();
Query qry = new Query(Service.Schema);
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
示例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);
}