本文整理汇总了C#中ServiceCollection.AddSingleton方法的典型用法代码示例。如果您正苦于以下问题:C# ServiceCollection.AddSingleton方法的具体用法?C# ServiceCollection.AddSingleton怎么用?C# ServiceCollection.AddSingleton使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ServiceCollection
的用法示例。
在下文中一共展示了ServiceCollection.AddSingleton方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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);
}
示例2: TestBase
public TestBase()
{
if (ServiceProvider == null)
{
var services = new ServiceCollection();
// set up empty in-memory test db
services
.AddEntityFrameworkInMemoryDatabase()
.AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase().UseInternalServiceProvider(services.BuildServiceProvider()));
// add identity service
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<AllReadyContext>();
var context = new DefaultHttpContext();
context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
services.AddSingleton<IHttpContextAccessor>(h => new HttpContextAccessor { HttpContext = context });
// Setup hosting environment
IHostingEnvironment hostingEnvironment = new HostingEnvironment();
hostingEnvironment.EnvironmentName = "Development";
services.AddSingleton(x => hostingEnvironment);
// set up service provider for tests
ServiceProvider = services.BuildServiceProvider();
}
}
示例3: AddWebEncoders_DoesNotOverrideExistingRegisteredEncoders
public void AddWebEncoders_DoesNotOverrideExistingRegisteredEncoders()
{
// Arrange
var serviceCollection = new ServiceCollection();
// Act
serviceCollection.AddSingleton<HtmlEncoder, HtmlTestEncoder>();
serviceCollection.AddSingleton<JavaScriptEncoder, JavaScriptTestEncoder>();
// we don't register an existing URL encoder
serviceCollection.AddWebEncoders(options =>
{
options.TextEncoderSettings = new TextEncoderSettings();
options.TextEncoderSettings.AllowCharacters("ace".ToCharArray()); // only these three chars are allowed
});
// Assert
var serviceProvider = serviceCollection.BuildServiceProvider();
var htmlEncoder = serviceProvider.GetRequiredService<HtmlEncoder>();
Assert.Equal("HtmlEncode[[abcde]]", htmlEncoder.Encode("abcde"));
var javaScriptEncoder = serviceProvider.GetRequiredService<JavaScriptEncoder>();
Assert.Equal("JavaScriptEncode[[abcde]]", javaScriptEncoder.Encode("abcde"));
var urlEncoder = serviceProvider.GetRequiredService<UrlEncoder>();
Assert.Equal("a%62c%64e", urlEncoder.Encode("abcde"));
}
示例4: 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.AddSingleton(service.ServiceType, serviceProvider.GetService(service.ServiceType));
}
}
else
{
clonedCollection.Add(service);
}
}
return clonedCollection;
}
示例5: 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);
}
示例6: 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"));
}
示例7: GetDefaultServices
public static IEnumerable<ServiceDescriptor> GetDefaultServices()
{
var services = new ServiceCollection();
//
// Discovery & Reflection.
//
// TODO: consider making above singleton
services.AddTransient<IAssemblyProvider, DefaultAssemblyProvider>();
services.AddTransient<ITypeActivator, DefaultTypeActivator>();
services.AddTransient<ITypeSelector, DefaultTypeSelector>();
services.AddTransient<ITypeService, DefaultTypeService>();
//
// Extensions
//
services.AddSingleton<IExtensionProvider<IRegisterServices>, DefaultExtensionProvider<IRegisterServices>>();
#if DNX
services.AddSingleton<IExtensionProvider<IRegisterMiddleware>, DefaultExtensionProvider<IRegisterMiddleware>>();
#endif
//
// Context.
//
services.AddSingleton(typeof(IContextData<>), typeof(ContextData<>));
services.AddSingleton<IGlimpseContextAccessor, DefaultGlimpseContextAccessor>();
//
// JSON.Net.
//
services.AddTransient<JsonSerializer, JsonSerializer>();
services.AddSingleton<IJsonSerializerProvider, DefaultJsonSerializerProvider>();
return services;
}
示例8: RegisterDIContainer
private void RegisterDIContainer()
{
var services = new ServiceCollection();
services.AddTransient<BooksViewModel>();
services.AddTransient<BookViewModel>();
services.AddSingleton<IBooksRepository, BooksRepository>();
services.AddSingleton<IEventAggregator, EventAggregator>();
Container = services.BuildServiceProvider();
}
示例9: CreateServices
private static IServiceProvider CreateServices()
{
var services = new ServiceCollection();
services.AddSingleton(new ObjectResultExecutor(
new TestOptionsManager<MvcOptions>(),
new TestHttpResponseStreamWriterFactory(),
NullLoggerFactory.Instance));
services.AddSingleton<ILoggerFactory>(NullLoggerFactory.Instance);
return services.BuildServiceProvider();
}
示例10: ManageControllerTest
public ManageControllerTest()
{
var efServiceProvider = new ServiceCollection().AddEntityFrameworkInMemoryDatabase().BuildServiceProvider();
var services = new ServiceCollection();
services.AddOptions();
services
.AddDbContext<MusicStoreContext>(b => b.UseInMemoryDatabase().UseInternalServiceProvider(efServiceProvider));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<MusicStoreContext>();
services.AddLogging();
services.AddOptions();
// IHttpContextAccessor is required for SignInManager, and UserManager
var context = new DefaultHttpContext();
context.Features.Set<IHttpAuthenticationFeature>(new HttpAuthenticationFeature() { Handler = new TestAuthHandler() });
services.AddSingleton<IHttpContextAccessor>(
new HttpContextAccessor()
{
HttpContext = context,
});
_serviceProvider = services.BuildServiceProvider();
}
示例11: Main
public async Task Main()
{
var services = new ServiceCollection();
services.AddDefaultServices(defaultProvider);
services.AddAssembly(typeof(Program).GetTypeInfo().Assembly);
services.AddOptions();
services.AddSingleton(x => MemoryCache.INSTANCE);
services.AddLogging();
services.AddGlobalConfiguration(environment);
var provider = services.BuildServiceProvider();
var logging = provider.GetService<ILoggerFactory>();
logging.AddProvider(provider.GetService<ISNSLoggerProvider>());
logging.AddConsole();
var cancellationSource = new CancellationTokenSource();
var taskRunner = new TaskRunner(logging.CreateLogger<TaskRunner>(), provider);
var tasks = taskRunner.RunTasksFromAssembly(typeof(Program).GetTypeInfo().Assembly, cancellationSource.Token);
Console.CancelKeyPress += (sender, e) =>
{
Console.WriteLine("Caught cancel, exiting...");
cancellationSource.Cancel();
};
await Task.WhenAll(tasks);
}
示例12: MultiRegistrationServiceTypes_AreRegistered_MultipleTimes
public void MultiRegistrationServiceTypes_AreRegistered_MultipleTimes()
{
// Arrange
var services = new ServiceCollection();
services.AddSingleton<IHostingEnvironment>(GetHostingEnvironment());
// 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
services.AddMvc();
// 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);
}
}
}
示例13: GetBindingContext
private static DefaultModelBindingContext GetBindingContext(Type modelType)
{
var metadataProvider = new TestModelMetadataProvider();
metadataProvider.ForType(modelType).BindingDetails(d => d.BindingSource = BindingSource.Services);
var modelMetadata = metadataProvider.GetMetadataForType(modelType);
var services = new ServiceCollection();
services.AddSingleton<IService>(new Service());
var bindingContext = new DefaultModelBindingContext
{
ActionContext = new ActionContext()
{
HttpContext = new DefaultHttpContext()
{
RequestServices = services.BuildServiceProvider(),
}
},
ModelMetadata = modelMetadata,
ModelName = "modelName",
FieldName = "modelName",
ModelState = new ModelStateDictionary(),
BinderModelName = modelMetadata.BinderModelName,
BindingSource = modelMetadata.BindingSource,
ValidationState = new ValidationStateDictionary(),
};
return bindingContext;
}
示例14: Main
static void Main(string[] args)
{
var serviceCollection = new ServiceCollection();
serviceCollection
.AddEntityFrameworkSqlServer();
serviceCollection.AddSingleton<SqlServerTypeMapper, CustomSqlServerTypeMapper>();
var options = new DbContextOptionsBuilder()
.UseInternalServiceProvider(serviceCollection.BuildServiceProvider())
.Options;
using (var db = new BloggingContext(options))
{
var serviceProvider = db.GetInfrastructure<IServiceProvider>();
var typeMapper = serviceProvider.GetService<IRelationalTypeMapper>();
Console.WriteLine($"Type mapper in use: {typeMapper.GetType().Name}");
Console.WriteLine($"Mapping for bool: {typeMapper.GetMapping(typeof(bool)).StoreType}");
Console.WriteLine($"Mapping for string: {typeMapper.GetMapping(typeof(string)).StoreType}");
db.Database.EnsureDeleted();
db.Database.EnsureCreated();
db.Blogs.Add(new Blog
{
Url = "http://sample.com",
Metadata = "<metadata><type>Wordpress</type><owner>rowan</owner></metadata>"
});
db.SaveChanges();
}
}
示例15: CreateTestServices
public static IServiceCollection CreateTestServices()
{
var services = new ServiceCollection();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddLogging();
services.AddIdentity<IdentityUser, IdentityRole>();
return services;
}