本文整理汇总了C#中ServiceCollection.AddInstance方法的典型用法代码示例。如果您正苦于以下问题:C# ServiceCollection.AddInstance方法的具体用法?C# ServiceCollection.AddInstance怎么用?C# ServiceCollection.AddInstance使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ServiceCollection
的用法示例。
在下文中一共展示了ServiceCollection.AddInstance方法的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.AddInstance<IKeyEscrowSink>(mockKeyEscrowSink1.Object);
serviceCollection.AddInstance<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: GetServiceCollectionWithContextAccessor
public static ServiceCollection GetServiceCollectionWithContextAccessor()
{
var services = new ServiceCollection();
IHttpContextAccessor contextAccessor = new HttpContextAccessor();
services.AddInstance<IHttpContextAccessor>(contextAccessor);
services.AddInstance<DiagnosticListener>(new DiagnosticListener("TestListener"));
return services;
}
示例3: CreateServices
private static IServiceProvider CreateServices()
{
var services = new ServiceCollection();
services.AddInstance(new ObjectResultExecutor(
new TestOptionsManager<MvcOptions>(),
new ActionBindingContextAccessor(),
new TestHttpResponseStreamWriterFactory(),
NullLoggerFactory.Instance));
services.AddInstance<ILoggerFactory>(NullLoggerFactory.Instance);
return services.BuildServiceProvider();
}
示例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.AddInstance(service.ServiceType, serviceProvider.GetService(service.ServiceType));
}
}
else {
clonedCollection.Add(service);
}
}
return clonedCollection;
}
示例5: GetBindingContext
private static ModelBindingContext 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.AddInstance<IService>(new Service());
var bindingContext = new ModelBindingContext
{
ModelMetadata = modelMetadata,
ModelName = "modelName",
FieldName = "modelName",
ModelState = new ModelStateDictionary(),
OperationBindingContext = new OperationBindingContext
{
ModelBinder = new HeaderModelBinder(),
MetadataProvider = metadataProvider,
HttpContext = new DefaultHttpContext()
{
RequestServices = services.BuildServiceProvider(),
},
},
BinderModelName = modelMetadata.BinderModelName,
BindingSource = modelMetadata.BindingSource,
ValidationState = new ValidationStateDictionary(),
};
return bindingContext;
}
示例6: Ctor_WithEncryptorButNoRepository_IgnoresFallback_FailsWithServiceNotFound
public void Ctor_WithEncryptorButNoRepository_IgnoresFallback_FailsWithServiceNotFound()
{
// Arrange
var mockFallback = new Mock<IDefaultKeyServices>();
mockFallback.Setup(o => o.GetKeyEncryptor()).Returns(new Mock<IXmlEncryptor>().Object);
mockFallback.Setup(o => o.GetKeyRepository()).Returns(new Mock<IXmlRepository>().Object);
var serviceCollection = new ServiceCollection();
serviceCollection.AddInstance<IDefaultKeyServices>(mockFallback.Object);
serviceCollection.AddInstance<IXmlEncryptor>(new Mock<IXmlEncryptor>().Object);
serviceCollection.AddInstance<IAuthenticatedEncryptorConfiguration>(new Mock<IAuthenticatedEncryptorConfiguration>().Object);
var services = serviceCollection.BuildServiceProvider();
// Act & assert - we don't care about exception type, only exception message
Exception ex = Assert.ThrowsAny<Exception>(() => new XmlKeyManager(services));
Assert.Contains("IXmlRepository", ex.Message);
}
示例7: CreateContainer
public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint)
{
IServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddInstance(settings);
serviceCollection.AddInstance(blueprint.Descriptor);
serviceCollection.AddInstance(blueprint);
// Sure this is right?
serviceCollection.AddInstance(_loggerFactory);
IServiceCollection moduleServiceCollection = new ServiceCollection();
foreach (var dependency in blueprint.Dependencies
.Where(t => typeof(IModule).IsAssignableFrom(t.Type))) {
moduleServiceCollection.AddScoped(typeof(IModule), dependency.Type);
}
var moduleServiceProvider = moduleServiceCollection.BuildShellServiceProviderWithHost(_serviceProvider);
foreach (var service in moduleServiceProvider.GetServices<IModule>()) {
service.Configure(serviceCollection);
}
foreach (var dependency in blueprint.Dependencies
.Where(t => !typeof(IModule).IsAssignableFrom(t.Type))) {
foreach (var interfaceType in dependency.Type.GetInterfaces()
.Where(itf => typeof(IDependency).IsAssignableFrom(itf))) {
_logger.LogDebug("Type: {0}, Interface Type: {1}", dependency.Type, interfaceType);
if (typeof(ISingletonDependency).IsAssignableFrom(interfaceType)) {
serviceCollection.AddSingleton(interfaceType, dependency.Type);
}
else if (typeof(IUnitOfWorkDependency).IsAssignableFrom(interfaceType)) {
serviceCollection.AddScoped(interfaceType, dependency.Type);
}
else if (typeof(ITransientDependency).IsAssignableFrom(interfaceType)) {
serviceCollection.AddTransient(interfaceType, dependency.Type);
}
else {
serviceCollection.AddScoped(interfaceType, dependency.Type);
}
}
}
return serviceCollection.BuildShellServiceProviderWithHost(_serviceProvider);
}
示例8: Encrypt_Decrypt_RoundTrips
public void Encrypt_Decrypt_RoundTrips()
{
// Arrange
var symmetricAlgorithm = new TripleDESCryptoServiceProvider();
symmetricAlgorithm.GenerateKey();
var serviceCollection = new ServiceCollection();
var mockInternalEncryptor = new Mock<IInternalCertificateXmlEncryptor>();
mockInternalEncryptor.Setup(o => o.PerformEncryption(It.IsAny<EncryptedXml>(), It.IsAny<XmlElement>()))
.Returns<EncryptedXml, XmlElement>((encryptedXml, element) =>
{
encryptedXml.AddKeyNameMapping("theKey", symmetricAlgorithm); // use symmetric encryption
return encryptedXml.Encrypt(element, "theKey");
});
serviceCollection.AddInstance<IInternalCertificateXmlEncryptor>(mockInternalEncryptor.Object);
var mockInternalDecryptor = new Mock<IInternalEncryptedXmlDecryptor>();
mockInternalDecryptor.Setup(o => o.PerformPreDecryptionSetup(It.IsAny<EncryptedXml>()))
.Callback<EncryptedXml>(encryptedXml =>
{
encryptedXml.AddKeyNameMapping("theKey", symmetricAlgorithm); // use symmetric encryption
});
serviceCollection.AddInstance<IInternalEncryptedXmlDecryptor>(mockInternalDecryptor.Object);
var services = serviceCollection.BuildServiceProvider();
var encryptor = new CertificateXmlEncryptor(services);
var decryptor = new EncryptedXmlDecryptor(services);
var originalXml = XElement.Parse(@"<mySecret value='265ee4ea-ade2-43b1-b706-09b259e58b6b' />");
// Act & assert - run through encryptor and make sure we get back <EncryptedData> element
var encryptedXmlInfo = encryptor.Encrypt(originalXml);
Assert.Equal(typeof(EncryptedXmlDecryptor), encryptedXmlInfo.DecryptorType);
Assert.Equal(XName.Get("EncryptedData", "http://www.w3.org/2001/04/xmlenc#"), encryptedXmlInfo.EncryptedElement.Name);
Assert.Equal("http://www.w3.org/2001/04/xmlenc#Element", (string)encryptedXmlInfo.EncryptedElement.Attribute("Type"));
Assert.DoesNotContain("265ee4ea-ade2-43b1-b706-09b259e58b6b", encryptedXmlInfo.EncryptedElement.ToString(), StringComparison.OrdinalIgnoreCase);
// Act & assert - run through decryptor and make sure we get back the original value
var roundTrippedElement = decryptor.Decrypt(encryptedXmlInfo.EncryptedElement);
XmlAssert.Equal(originalXml, roundTrippedElement);
}
示例9: Ctor_WithoutEncryptorOrRepository_UsesFallback
public void Ctor_WithoutEncryptorOrRepository_UsesFallback()
{
// Arrange
var expectedEncryptor = new Mock<IXmlEncryptor>().Object;
var expectedRepository = new Mock<IXmlRepository>().Object;
var mockFallback = new Mock<IDefaultKeyServices>();
mockFallback.Setup(o => o.GetKeyEncryptor()).Returns(expectedEncryptor);
mockFallback.Setup(o => o.GetKeyRepository()).Returns(expectedRepository);
var serviceCollection = new ServiceCollection();
serviceCollection.AddInstance<IDefaultKeyServices>(mockFallback.Object);
serviceCollection.AddInstance<IAuthenticatedEncryptorConfiguration>(new Mock<IAuthenticatedEncryptorConfiguration>().Object);
var services = serviceCollection.BuildServiceProvider();
// Act
var keyManager = new XmlKeyManager(services);
// Assert
Assert.Same(expectedEncryptor, keyManager.KeyEncryptor);
Assert.Same(expectedRepository, keyManager.KeyRepository);
}
示例10: GetServiceProvider
public static IServiceProvider GetServiceProvider()
{
var services = new ServiceCollection();
services.AddMvc();
services.AddEntityFramework()
.AddInMemoryDatabase()
.AddDbContext<ChatLeIdentityDbContext>(options => options.UseInMemoryDatabase());
services.AddInstance<ILoggerFactory>(new LoggerFactory());
services.AddIdentity<ChatLeUser, IdentityRole>();
services.AddChatLe();
return services.BuildServiceProvider();
}
示例11: GetActivator_ServiceProviderHasActivator_ReturnsSameInstance
public void GetActivator_ServiceProviderHasActivator_ReturnsSameInstance()
{
// Arrange
var expectedActivator = new Mock<IActivator>().Object;
var serviceCollection = new ServiceCollection();
serviceCollection.AddInstance<IActivator>(expectedActivator);
// Act
var actualActivator = serviceCollection.BuildServiceProvider().GetActivator();
// Assert
Assert.Same(expectedActivator, actualActivator);
}
示例12: OnValidatePrincipalTestSuccess
public async Task OnValidatePrincipalTestSuccess(bool isPersistent)
{
var user = new TestUser("test");
var userManager = MockHelpers.MockUserManager<TestUser>();
var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>();
var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.Zero };
var options = new Mock<IOptions<IdentityOptions>>();
options.Setup(a => a.Value).Returns(identityOptions);
var httpContext = new Mock<HttpContext>();
var contextAccessor = new Mock<IHttpContextAccessor>();
contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
var id = new ClaimsIdentity(identityOptions.Cookies.ApplicationCookieAuthenticationScheme);
id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
var principal = new ClaimsPrincipal(id);
var properties = new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow, IsPersistent = isPersistent };
var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object,
contextAccessor.Object, claimsManager.Object, options.Object, null);
signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).ReturnsAsync(user).Verifiable();
signInManager.Setup(s => s.CreateUserPrincipalAsync(user)).ReturnsAsync(principal).Verifiable();
var services = new ServiceCollection();
services.AddInstance(options.Object);
services.AddInstance(signInManager.Object);
services.AddInstance<ISecurityStampValidator>(new SecurityStampValidator<TestUser>());
httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
var ticket = new AuthenticationTicket(principal,
properties,
identityOptions.Cookies.ApplicationCookieAuthenticationScheme);
var context = new CookieValidatePrincipalContext(httpContext.Object, ticket, new CookieAuthenticationOptions());
Assert.NotNull(context.Properties);
Assert.NotNull(context.Options);
Assert.NotNull(context.Principal);
await
SecurityStampValidator.ValidatePrincipalAsync(context);
Assert.NotNull(context.Principal);
signInManager.VerifyAll();
}
示例13: StartupWithNoConfigureThrows
public void StartupWithNoConfigureThrows()
{
var serviceCollection = new ServiceCollection();
serviceCollection.AddInstance<IFakeStartupCallback>(this);
var services = serviceCollection.BuildServiceProvider();
var diagnosticMessages = new List<string>();
var hostingEnv = new HostingEnvironment { EnvironmentName = "Boom" };
var loader = new StartupLoader(services, hostingEnv);
var type = loader.FindStartupType("Microsoft.AspNet.Hosting.Tests", diagnosticMessages);
var ex = Assert.Throws<InvalidOperationException>(() => loader.LoadMethods(type, diagnosticMessages));
Assert.Equal("A public method named 'ConfigureBoom' or 'Configure' could not be found in the 'Microsoft.AspNet.Hosting.Fakes.StartupBoom' type.", ex.Message);
}
示例14: CreateServices
private static IServiceProvider CreateServices()
{
var options = new TestOptionsManager<MvcOptions>();
options.Value.OutputFormatters.Add(new StringOutputFormatter());
options.Value.OutputFormatters.Add(new JsonOutputFormatter());
var services = new ServiceCollection();
services.AddInstance(new ObjectResultExecutor(
options,
new ActionBindingContextAccessor(),
new TestHttpResponseStreamWriterFactory(),
NullLoggerFactory.Instance));
return services.BuildServiceProvider();
}
示例15: ShapeFactoryTests
public ShapeFactoryTests()
{
IServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddScoped<ILoggerFactory, StubLoggerFactory>();
serviceCollection.AddScoped<IShapeFactory, DefaultShapeFactory>();
serviceCollection.AddScoped<IExtensionManager, StubExtensionManager>();
serviceCollection.AddScoped<IShapeTableManager, TestShapeTableManager>();
var defaultShapeTable = new ShapeTable {
Descriptors = new Dictionary<string, ShapeDescriptor>(StringComparer.OrdinalIgnoreCase),
Bindings = new Dictionary<string, ShapeBinding>(StringComparer.OrdinalIgnoreCase)
};
serviceCollection.AddInstance(defaultShapeTable);
_serviceProvider = serviceCollection.BuildServiceProvider();
}