本文整理汇总了C#中Microsoft.Framework.DependencyInjection.ServiceCollection类的典型用法代码示例。如果您正苦于以下问题:C# ServiceCollection类的具体用法?C# ServiceCollection怎么用?C# ServiceCollection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ServiceCollection类属于Microsoft.Framework.DependencyInjection命名空间,在下文中一共展示了ServiceCollection类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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);
}
}
}
开发者ID:Nyaoso,项目名称:EntityFramework,代码行数:34,代码来源:SequentialGuidEndToEndTest.cs
示例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;
}
开发者ID:vebin,项目名称:Brochard,代码行数:26,代码来源:LoggerFactoryExtensions.cs
示例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);
}
开发者ID:CodeComb,项目名称:Localization,代码行数:32,代码来源:JsonCollectionTests.cs
示例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);
}
开发者ID:RehanSaeed,项目名称:Mvc,代码行数:25,代码来源:DefaultTagHelperActivatorTest.cs
示例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);
}
}
}
开发者ID:aishaloshik,项目名称:EntityFramework,代码行数:31,代码来源:SequentialGuidEndToEndTest.cs
示例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);
}
}
}
开发者ID:4myBenefits,项目名称:Mvc,代码行数:26,代码来源:MvcCoreServiceCollectionExtensionsTest.cs
示例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));
}
开发者ID:491134648,项目名称:EntityFramework,代码行数:26,代码来源:RelationalDatabaseTest.cs
示例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);
}
开发者ID:RehanSaeed,项目名称:Mvc,代码行数:31,代码来源:MvcServiceCollectionExtensionsTest.cs
示例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();
}
开发者ID:itomek,项目名称:WebHooks,代码行数:12,代码来源:HttpConfigurationExtensions.cs
示例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"));
}
}
开发者ID:sherif-elmetainy,项目名称:DI,代码行数:29,代码来源:DecoratorTests.cs
示例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);
}
开发者ID:notami18,项目名称:Mvc,代码行数:25,代码来源:CompareAttributeAdapterTest.cs
示例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);
}
开发者ID:qiudesong,项目名称:Localization,代码行数:26,代码来源:LocalizationServiceCollectionExtensionsTest.cs
示例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]);
}
开发者ID:EgoDust,项目名称:HttpAbstractions,代码行数:60,代码来源:UseWithServicesTests.cs
示例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;
}
开发者ID:Kieranties,项目名称:MessagingPlayground,代码行数:36,代码来源:Program.cs
示例16: 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
示例17: Initializes_all_entity_set_properties_with_setters
public void Initializes_all_entity_set_properties_with_setters()
{
var setFinderMock = new Mock<IDbSetFinder>();
setFinderMock.Setup(m => m.FindSets(It.IsAny<DbContext>())).Returns(
new[]
{
new DbSetProperty(typeof(JustAContext), "One", typeof(string), hasSetter: true),
new DbSetProperty(typeof(JustAContext), "Two", typeof(object), hasSetter: true),
new DbSetProperty(typeof(JustAContext), "Three", typeof(string), hasSetter: true),
new DbSetProperty(typeof(JustAContext), "Four", typeof(string), hasSetter: false)
});
var customServices = new ServiceCollection()
.AddInstance<IDbSetInitializer>(new DbSetInitializer(setFinderMock.Object, new ClrPropertySetterSource(), new DbSetSource()));
var serviceProvider = TestHelpers.Instance.CreateServiceProvider(customServices);
using (var context = new JustAContext(serviceProvider, new EntityOptionsBuilder().Options))
{
Assert.NotNull(context.One);
Assert.NotNull(context.GetTwo());
Assert.NotNull(context.Three);
Assert.Null(context.Four);
}
}
开发者ID:aishaloshik,项目名称:EntityFramework,代码行数:25,代码来源:DbSetInitializerTest.cs
示例18: Non_generic_GetRequiredService_throws_useful_exception_if_service_not_registered
public void Non_generic_GetRequiredService_throws_useful_exception_if_service_not_registered()
{
var serviceProvider = new ServiceCollection().BuildServiceProvider();
Assert.Throws<InvalidOperationException>(
() => serviceProvider.GetRequiredService(typeof(IPilkington)));
}
开发者ID:thegido,项目名称:EntityFramework,代码行数:7,代码来源:ServiceProviderExtensionsTest.cs
示例19: Can_use_explicit_values
public async Task Can_use_explicit_values()
{
var serviceProvider = new ServiceCollection()
.AddEntityFramework()
.AddSqlServer()
.ServiceCollection()
.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:aishaloshik,项目名称:EntityFramework,代码行数:34,代码来源:SequentialGuidEndToEndTest.cs
示例20: BindModel_CallsBindAsync_OnProvidedModelBinder
public async Task BindModel_CallsBindAsync_OnProvidedModelBinder()
{
// Arrange
var bindingContext = GetBindingContext(typeof(Person), binderType: typeof(TrueModelBinder));
var model = new Person();
var serviceProvider = new ServiceCollection()
.AddSingleton(typeof(IModelBinder))
.BuildServiceProvider();
bindingContext.OperationBindingContext.HttpContext.RequestServices = serviceProvider;
var binder = new BinderTypeBasedModelBinder();
// Act
var binderResult = await binder.BindModelAsync(bindingContext);
// Assert
var p = (Person)binderResult.Model;
Assert.Equal(model.Age, p.Age);
Assert.Equal(model.Name, p.Name);
Assert.NotNull(binderResult.ValidationNode);
Assert.Equal(bindingContext.ModelName, binderResult.ValidationNode.Key);
Assert.Same(binderResult.Model, binderResult.ValidationNode.Model);
}
开发者ID:RehanSaeed,项目名称:Mvc,代码行数:25,代码来源:BinderTypeBasedModelBinderModelBinderTest.cs
注:本文中的Microsoft.Framework.DependencyInjection.ServiceCollection类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论