本文整理汇总了C#中ServiceCollection.Add方法的典型用法代码示例。如果您正苦于以下问题:C# ServiceCollection.Add方法的具体用法?C# ServiceCollection.Add怎么用?C# ServiceCollection.Add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ServiceCollection
的用法示例。
在下文中一共展示了ServiceCollection.Add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Add_AddsMultipleDescriptorToServiceDescriptors
public void Add_AddsMultipleDescriptorToServiceDescriptors()
{
// Arrange
var serviceCollection = new ServiceCollection();
var descriptor1 = new ServiceDescriptor(typeof(IFakeService), new FakeService());
var descriptor2 = new ServiceDescriptor(typeof(IFactoryService), typeof(TransientFactoryService), ServiceLifetime.Transient);
// Act
serviceCollection.Add(descriptor1);
serviceCollection.Add(descriptor2);
// Assert
Assert.Equal(2, serviceCollection.Count);
Assert.Equal(new[] { descriptor1, descriptor2 }, serviceCollection);
}
示例2: 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);
}
}
}
示例3: 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;
}
示例4: 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);
}
示例5: ServiceDescriptors_AllowsRemovingPreviousRegisteredServices
public void ServiceDescriptors_AllowsRemovingPreviousRegisteredServices()
{
// Arrange
var serviceCollection = new ServiceCollection();
var descriptor1 = new ServiceDescriptor(typeof(IFakeService), new FakeService());
var descriptor2 = new ServiceDescriptor(typeof(IFactoryService), typeof(TransientFactoryService), ServiceLifetime.Transient);
// Act
serviceCollection.Add(descriptor1);
serviceCollection.Add(descriptor2);
serviceCollection.Remove(descriptor1);
// Assert
var result = Assert.Single(serviceCollection);
Assert.Same(result, descriptor2);
}
示例6: WrappingServiceProvider
// Need full wrap for generics like IOptions
public WrappingServiceProvider(IServiceProvider fallback, IServiceCollection replacedServices)
{
var services = new ServiceCollection();
var manifest = fallback.GetRequiredService<IRuntimeServices>();
foreach (var service in manifest.Services) {
services.AddTransient(service, sp => fallback.GetService(service));
}
services.Add(replacedServices);
_services = services.BuildServiceProvider();
}
示例7: Add_AddsDescriptorToServiceDescriptors
public void Add_AddsDescriptorToServiceDescriptors()
{
// Arrange
var serviceCollection = new ServiceCollection();
var descriptor = new ServiceDescriptor(typeof(IFakeService), new FakeService());
// Act
serviceCollection.Add(descriptor);
// Assert
var result = Assert.Single(serviceCollection);
Assert.Same(result, descriptor);
}
示例8: SingleRegistrationServiceTypes_AreNotRegistered_MultipleTimes
public void SingleRegistrationServiceTypes_AreNotRegistered_MultipleTimes()
{
// Arrange
var services = new ServiceCollection();
// Register a mock implementation of each service, AddMvcServices should not replace it.
foreach (var serviceType in SingleRegistrationServiceTypes)
{
var mockType = typeof(Mock<>).MakeGenericType(serviceType);
services.Add(ServiceDescriptor.Transient(serviceType, mockType));
}
// Act
MvcCoreServiceCollectionExtensions.AddMvcCoreServices(services);
// Assert
foreach (var singleRegistrationType in SingleRegistrationServiceTypes)
{
AssertServiceCountEquals(services, singleRegistrationType, 1);
}
}
示例9: GetServiceProvider
private static ServiceProvider GetServiceProvider(params ServiceDescriptor[] descriptors)
{
var collection = new ServiceCollection();
foreach (var descriptor in descriptors)
{
collection.Add(descriptor);
}
return (ServiceProvider)collection.BuildServiceProvider();
}
示例10: Main
private static void Main(string[] args)
{
SetupConsole();
try
{
var config = new FilterConfig("Config\\Filter.xml");
//Logger
foreach (var logger in config.Logger)
{
StaticLogger.Create(logger.Key);
StaticLogger.SetLogLevel(logger.Value.Ordinal, logger.Key);
}
StaticLogger.SetInstance();
//StaticLogger.Instance.Trace("Trace");
//StaticLogger.Instance.Debug("Debug");
//StaticLogger.Instance.Info("Info");
//StaticLogger.Instance.Warn("Warn");
//StaticLogger.Instance.Error("Error");
//StaticLogger.Instance.Fatal("Fatal");
//Services
_serviceCollection = new ServiceCollection();
foreach (var serviceSettings in config.Services)
{
var service = new Service(serviceSettings.Value);
_serviceCollection.Add(service);
}
//Plugins
var pluginManager = new PluginManager(config.Plugins);
foreach (var service in _serviceCollection)
{
pluginManager.RegisterService(service);
}
var pluginCount = pluginManager.Load();
StaticLogger.Instance.Info($"{pluginCount} plugins registered.");
//Start services
foreach (var service in _serviceCollection)
{
var result = service.Start();
if (result == false)
StaticLogger.Instance.Fatal($"Failed to start {service.Settings.Name}, check Filter.xml and prev. errors");
}
StaticLogger.Instance.Info("Successfully initilized.");
Console.Beep();
while (true)
{
var line = Console.ReadLine();
if (line == "exit" || line == "quit")
break;
}
foreach (var service in _serviceCollection)
{
service.Stop();
}
}
catch (Exception ex)
{
Console.Beep();
Console.WriteLine("Something fucked up really hard, please check Filter.xml");
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
Console.Beep();
Console.ReadLine();
}
}
示例11: RegisterNeededServices
/// <summary>
/// Register the needed services
/// </summary>
/// <param name="services"></param>
/// <param name="project"></param>
private static void RegisterNeededServices(ServiceCollection services, IProject project)
{
ServiceCollection rootServices = ApplicationContext.Current.RootWorkItem.Services;
rootServices.Add<IProjectContextService>(new SimpleProjectContextService(project));
rootServices.AddNew<ProjectLocalizationService>();
rootServices.Add<IPortalDeploymentService>(new PortalDeploymentService());
ITypeResolutionService resService = new TypeResolutionService();
services.Add(typeof(ITypeResolutionService), resService);
services.Add(typeof(ITypeDiscoveryService), resService);
}
示例12: Replace_ReplacesFirstServiceWithMatchingServiceType
public void Replace_ReplacesFirstServiceWithMatchingServiceType()
{
// Arrange
var collection = new ServiceCollection();
var descriptor1 = new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient);
var descriptor2 = new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient);
collection.Add(descriptor1);
collection.Add(descriptor2);
var descriptor3 = new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Singleton);
// Act
collection.Replace(descriptor3);
// Assert
Assert.Equal(new[] { descriptor2, descriptor3 }, collection);
}
示例13: Replace_AddsServiceIfServiceTypeIsNotRegistered
public void Replace_AddsServiceIfServiceTypeIsNotRegistered()
{
// Arrange
var collection = new ServiceCollection();
var descriptor1 = new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient);
var descriptor2 = new ServiceDescriptor(typeof(IFakeOuterService), typeof(FakeOuterService), ServiceLifetime.Transient);
collection.Add(descriptor1);
// Act
collection.Replace(descriptor2);
// Assert
Assert.Equal(new[] { descriptor1, descriptor2 }, collection);
}
示例14: AddSequence_AddsServicesToCollection
public void AddSequence_AddsServicesToCollection()
{
// Arrange
var collection = new ServiceCollection();
var descriptor1 = new ServiceDescriptor(typeof(IFakeService), typeof(FakeService), ServiceLifetime.Transient);
var descriptor2 = new ServiceDescriptor(typeof(IFakeOuterService), typeof(FakeOuterService), ServiceLifetime.Transient);
var descriptors = new[] { descriptor1, descriptor2 };
// Act
var result = collection.Add(descriptors);
// Assert
Assert.Equal(descriptors, collection);
}
示例15: TryAdd_WithType_DoesNotAddDuplicate
public void TryAdd_WithType_DoesNotAddDuplicate(
Action<IServiceCollection> addAction,
Type expectedServiceType,
Type expectedImplementationType,
ServiceLifetime expectedLifetime)
{
// Arrange
var collection = new ServiceCollection();
collection.Add(ServiceDescriptor.Transient(expectedServiceType, expectedServiceType));
// Act
addAction(collection);
// Assert
var descriptor = Assert.Single(collection);
Assert.Equal(expectedServiceType, descriptor.ServiceType);
Assert.Same(expectedServiceType, descriptor.ImplementationType);
Assert.Equal(ServiceLifetime.Transient, descriptor.Lifetime);
}