本文整理汇总了C#中Microsoft.Framework.DependencyInjection.ServiceCollection类的典型用法代码示例。如果您正苦于以下问题:C# ServiceCollection类的具体用法?C# ServiceCollection怎么用?C# ServiceCollection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ServiceCollection类属于Microsoft.Framework.DependencyInjection命名空间,在下文中一共展示了ServiceCollection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Can_use_sequential_GUID_end_to_end_async
public async Task Can_use_sequential_GUID_end_to_end_async()
{
var serviceProvider = new ServiceCollection()
.AddEntityFramework()
.AddSqlServer()
.ServiceCollection
.BuildServiceProvider();
using (var context = new BronieContext(serviceProvider, "GooieBronies"))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
for (var i = 0; i < 50; i++)
{
await context.AddAsync(new Pegasus { Name = "Rainbow Dash " + i });
}
await context.SaveChangesAsync();
}
using (var context = new BronieContext(serviceProvider, "GooieBronies"))
{
// TODO: Currently test passes because SQL Server happens to return values in
// inserted order. When OrderBy is done on server it should be added to the query.
//var pegasuses = await context.Pegasuses.OrderBy(e => e.Id).ToListAsync();
var pegasuses = await context.Pegasuses.ToListAsync();
for (var i = 0; i < 50; i++)
{
Assert.Equal("Rainbow Dash " + i, pegasuses[i].Name);
}
}
}
示例2: AddOrchardLogging
public static ILoggerFactory AddOrchardLogging(
[NotNull] this ILoggerFactory loggingFactory,
IServiceProvider serviceProvider)
{
/* TODO (ngm): Abstract this logger stuff outta here! */
var loader = serviceProvider.GetRequiredService<IExtensionLoader>();
var manager = serviceProvider.GetRequiredService<IExtensionManager>();
var descriptor = manager.GetExtension("Orchard.Logging.Console");
var entry = loader.Load(descriptor);
var loggingInitiatorTypes = entry
.Assembly
.ExportedTypes
.Where(et => typeof(ILoggingInitiator).IsAssignableFrom(et));
IServiceCollection loggerCollection = new ServiceCollection();
foreach (var initiatorType in loggingInitiatorTypes) {
loggerCollection.AddScoped(typeof(ILoggingInitiator), initiatorType);
}
var moduleServiceProvider = loggerCollection.BuildShellServiceProviderWithHost(serviceProvider);
foreach (var service in moduleServiceProvider.GetServices<ILoggingInitiator>()) {
service.Initialize(loggingFactory);
}
return loggingFactory;
}
示例3: 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);
}
示例4: Activate_InitializesTagHelpers
public void Activate_InitializesTagHelpers(string name, int number)
{
// Arrange
var services = new ServiceCollection();
services.InitializeTagHelper<TestTagHelper>((h, vc) =>
{
h.Name = name;
h.Number = number;
h.ViewDataValue = vc.ViewData["TestData"];
});
var httpContext = MakeHttpContext(services.BuildServiceProvider());
var viewContext = MakeViewContext(httpContext);
var viewDataValue = new object();
viewContext.ViewData.Add("TestData", viewDataValue);
var activator = new DefaultTagHelperActivator();
var helper = new TestTagHelper();
// Act
activator.Activate(helper, viewContext);
// Assert
Assert.Equal(name, helper.Name);
Assert.Equal(number, helper.Number);
Assert.Same(viewDataValue, helper.ViewDataValue);
}
示例5: GetServiceCollectionWithContextAccessor
public static ServiceCollection GetServiceCollectionWithContextAccessor()
{
var services = new ServiceCollection();
IHttpContextAccessor contextAccessor = new HttpContextAccessor();
services.AddInstance<IHttpContextAccessor>(contextAccessor);
return services;
}
开发者ID:modulexcite,项目名称:ApplicationInsights-aspnet5,代码行数:7,代码来源:ApplicationInsightsExtensionsTests.cs
示例6: Can_use_sequential_GUID_end_to_end_async
public async Task Can_use_sequential_GUID_end_to_end_async()
{
var serviceProvider = new ServiceCollection()
.AddEntityFramework()
.AddSqlServer()
.ServiceCollection()
.BuildServiceProvider();
using (var context = new BronieContext(serviceProvider, "GooieBronies"))
{
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
for (var i = 0; i < 50; i++)
{
context.Add(new Pegasus { Name = "Rainbow Dash " + i });
}
await context.SaveChangesAsync();
}
using (var context = new BronieContext(serviceProvider, "GooieBronies"))
{
var pegasuses = await context.Pegasuses.OrderBy(e => e.Id).ToListAsync();
for (var i = 0; i < 50; i++)
{
Assert.Equal("Rainbow Dash " + i, pegasuses[i].Name);
}
}
}
示例7: 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);
}
}
}
示例8: 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));
}
示例9: WithControllersAsServices_ScansControllersFromSpecifiedAssemblies
public void WithControllersAsServices_ScansControllersFromSpecifiedAssemblies()
{
// Arrange
var collection = new ServiceCollection();
var assemblies = new[] { GetType().Assembly };
var controllerTypes = new[] { typeof(ControllerTypeA), typeof(TypeBController) };
// Act
MvcServiceCollectionExtensions.WithControllersAsServices(collection, assemblies);
// Assert
var services = collection.ToList();
Assert.Equal(4, services.Count);
Assert.Equal(typeof(ControllerTypeA), services[0].ServiceType);
Assert.Equal(typeof(ControllerTypeA), services[0].ImplementationType);
Assert.Equal(ServiceLifetime.Transient, services[0].Lifetime);
Assert.Equal(typeof(TypeBController), services[1].ServiceType);
Assert.Equal(typeof(TypeBController), services[1].ImplementationType);
Assert.Equal(ServiceLifetime.Transient, services[1].Lifetime);
Assert.Equal(typeof(IControllerActivator), services[2].ServiceType);
Assert.Equal(typeof(ServiceBasedControllerActivator), services[2].ImplementationType);
Assert.Equal(ServiceLifetime.Transient, services[2].Lifetime);
Assert.Equal(typeof(IControllerTypeProvider), services[3].ServiceType);
var typeProvider = Assert.IsType<FixedSetControllerTypeProvider>(services[3].ImplementationInstance);
Assert.Equal(controllerTypes, typeProvider.ControllerTypes.OrderBy(c => c.Name));
Assert.Equal(ServiceLifetime.Singleton, services[3].Lifetime);
}
示例10: GetDataProtectionProvider
/// <summary>
/// This follows the same initialization that is provided when <see cref="IDataProtectionProvider"/>
/// is initialized within ASP.NET 5.0 Dependency Injection.
/// </summary>
/// <returns>A fully initialized <see cref="IDataProtectionProvider"/>.</returns>
internal static IDataProtectionProvider GetDataProtectionProvider()
{
ServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddDataProtection();
IServiceProvider services = serviceCollection.BuildServiceProvider();
return services.GetDataProtectionProvider();
}
示例11: TestHelloNonGenericServiceDecoratorNoInterface
public void TestHelloNonGenericServiceDecoratorNoInterface()
{
var services = new ServiceCollection();
services.AddInstance<IHelloService>(new HelloService());
services.AddSingleton<IHelloService>(sp => new HelloService());
services.AddScoped<IHelloService>(sp => new HelloService());
services.AddTransient<IHelloService>(sp => new HelloService());
services.AddSingleton<IHelloService, HelloService>();
services.AddScoped<IHelloService, HelloService>();
services.AddTransient<IHelloService, HelloService>();
services.AddDecorator(typeof(IHelloService), (sp, s) => new HelloServiceDecoratorNoInterface((IHelloService)s));
var provider = services.BuildServiceProvider();
var helloServices = provider.GetRequiredServices<IHelloService>();
Assert.NotNull(helloServices);
var collection = helloServices as IHelloService[] ?? helloServices.ToArray();
Assert.Equal(7, collection.Length);
Assert.NotEmpty(collection);
foreach (var helloService in collection)
{
Assert.NotNull(helloService);
Assert.Equal("Decorated without interface: Hello world.", helloService.SayHello("world"));
}
}
示例12: 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);
}
示例13: AddLocalizationWithLocalizationOptions_AddsNeededServices
public void AddLocalizationWithLocalizationOptions_AddsNeededServices()
{
// Arrange
var collection = new ServiceCollection();
// Act
collection.AddLocalization(options => options.ResourcesPath = "Resources");
// Assert
var services = collection.ToList();
Assert.Equal(4, services.Count);
Assert.Equal(typeof(IStringLocalizerFactory), services[0].ServiceType);
Assert.Equal(typeof(ResourceManagerStringLocalizerFactory), services[0].ImplementationType);
Assert.Equal(ServiceLifetime.Singleton, services[0].Lifetime);
Assert.Equal(typeof(IStringLocalizer<>), services[1].ServiceType);
Assert.Equal(typeof(StringLocalizer<>), services[1].ImplementationType);
Assert.Equal(ServiceLifetime.Transient, services[1].Lifetime);
Assert.Equal(typeof(IConfigureOptions<LocalizationOptions>), services[2].ServiceType);
Assert.Equal(ServiceLifetime.Singleton, services[2].Lifetime);
Assert.Equal(typeof(IOptions<>), services[3].ServiceType);
Assert.Equal(ServiceLifetime.Singleton, services[3].Lifetime);
}
示例14: ServicesArePerRequest
public async Task ServicesArePerRequest()
{
var services = new ServiceCollection()
.AddScoped<ITestService, TestService>()
.BuildServiceProvider();
var builder = new ApplicationBuilder(services);
builder.Use(async (ctx, next) =>
{
var serviceScopeFactory = services.GetRequiredService<IServiceScopeFactory>();
using (var serviceScope = serviceScopeFactory.CreateScope())
{
var priorApplicationServices = ctx.ApplicationServices;
var priorRequestServices = ctx.ApplicationServices;
ctx.ApplicationServices = services;
ctx.RequestServices = serviceScope.ServiceProvider;
try
{
await next();
}
finally
{
ctx.ApplicationServices = priorApplicationServices;
ctx.RequestServices = priorRequestServices;
}
}
});
var testServicesA = new List<ITestService>();
builder.Use(async (HttpContext ctx, Func<Task> next, ITestService testService) =>
{
testServicesA.Add(testService);
await next();
});
var testServicesB = new List<ITestService>();
builder.Use<ITestService>(async (ctx, next, testService) =>
{
testServicesB.Add(testService);
await next();
});
var app = builder.Build();
await app(new DefaultHttpContext());
await app(new DefaultHttpContext());
Assert.Equal(2, testServicesA.Count);
Assert.IsType<TestService>(testServicesA[0]);
Assert.IsType<TestService>(testServicesA[1]);
Assert.Equal(2, testServicesB.Count);
Assert.IsType<TestService>(testServicesB[0]);
Assert.IsType<TestService>(testServicesB[1]);
Assert.Same(testServicesA[0], testServicesB[0]);
Assert.Same(testServicesA[1], testServicesB[1]);
Assert.NotSame(testServicesA[0], testServicesA[1]);
Assert.NotSame(testServicesB[0], testServicesB[1]);
}
示例15: 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;
}