本文整理汇总了C#中Microsoft.Framework.DependencyInjection.ServiceCollection.AddSingleton方法的典型用法代码示例。如果您正苦于以下问题:C# ServiceCollection.AddSingleton方法的具体用法?C# ServiceCollection.AddSingleton怎么用?C# ServiceCollection.AddSingleton使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.Framework.DependencyInjection.ServiceCollection
的用法示例。
在下文中一共展示了ServiceCollection.AddSingleton方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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"));
}
示例2: ActivityApiControllerTest
public ActivityApiControllerTest()
{
if (_serviceProvider == null)
{
var services = new ServiceCollection();
// Add Configuration to the Container
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddEnvironmentVariables();
IConfiguration configuration = builder.Build();
services.AddSingleton(x => configuration);
// Add EF (Full DB, not In-Memory)
services.AddEntityFramework()
.AddInMemoryDatabase()
.AddDbContext<AllReadyContext>(options => options.UseInMemoryDatabase());
// Setup hosting environment
IHostingEnvironment hostingEnvironment = new HostingEnvironment();
hostingEnvironment.EnvironmentName = "Development";
services.AddSingleton(x => hostingEnvironment);
_serviceProvider = services.BuildServiceProvider();
}
}
示例3: CreateHttpContextAccessor
public static HttpContextAccessor CreateHttpContextAccessor(RequestTelemetry requestTelemetry = null, ActionContext actionContext = null)
{
var services = new ServiceCollection();
var request = new DefaultHttpContext().Request;
request.Method = "GET";
request.Path = new PathString("/Test");
var contextAccessor = new HttpContextAccessor() { HttpContext = request.HttpContext };
services.AddSingleton<IHttpContextAccessor>(contextAccessor);
if (actionContext != null)
{
var si = new ActionContextAccessor();
si.ActionContext = actionContext;
services.AddSingleton<IActionContextAccessor>(si);
}
if (requestTelemetry != null)
{
services.AddSingleton<RequestTelemetry>(requestTelemetry);
}
IServiceProvider serviceProvider = services.BuildServiceProvider();
contextAccessor.HttpContext.RequestServices = serviceProvider;
return contextAccessor;
}
示例4: 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"));
}
}
示例5: RegisterServices
private void RegisterServices()
{
ServiceCollection services = new ServiceCollection();
services.AddSingleton<IBooksService, BooksService>();
services.AddSingleton<IMessagingService, WPFMessagingService>();
services.AddTransient<BooksViewModel>();
services.AddTransient<BookViewModel>();
services.AddTransient<RandomViewModel>();
Container = services.BuildServiceProvider();
}
示例6: GetDefaultServices
public static IEnumerable<ServiceDescriptor> GetDefaultServices()
{
var services = new ServiceCollection();
//
// Discovery & Reflection.
//
services.AddTransient<ITypeActivator, DefaultTypeActivator>();
services.AddTransient<ITypeSelector, DefaultTypeSelector>();
services.AddTransient<IAssemblyProvider, DefaultAssemblyProvider>();
services.AddTransient<ITypeService, DefaultTypeService>();
// TODO: consider making above singleton
//
// Context.
//
services.AddTransient(typeof(IContextData<>), typeof(ContextData<>));
//
// Messages.
//
services.AddSingleton<IMessageConverter, DefaultMessageConverter>();
//
// JSON.Net.
//
services.AddTransient<JsonSerializer, JsonSerializer>();
return services;
}
示例7: GetDefaultServices
public static IServiceCollection GetDefaultServices()
{
var services = new ServiceCollection();
//
// Options
//
services.AddTransient<IConfigureOptions<GlimpseAgentWebOptions>, GlimpseAgentWebOptionsSetup>();
services.AddSingleton<IRequestIgnorerUriProvider, DefaultRequestIgnorerUriProvider>();
services.AddSingleton<IRequestIgnorerStatusCodeProvider, DefaultRequestIgnorerStatusCodeProvider>();
services.AddSingleton<IRequestIgnorerContentTypeProvider, DefaultRequestIgnorerContentTypeProvider>();
services.AddSingleton<IRequestIgnorerProvider, DefaultRequestIgnorerProvider>();
services.AddSingleton<IRequestProfilerProvider, DefaultRequestProfilerProvider>();
return services;
}
示例8: 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;
}
示例9: CreateTestServices
public static IServiceCollection CreateTestServices()
{
var services = new ServiceCollection();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddLogging();
services.AddIdentity<IdentityUser, IdentityRole>();
return services;
}
示例10: ConfigureServices
public void ConfigureServices()
{
IServiceProvider mainProv = CallContextServiceLocator.Locator.ServiceProvider;
IApplicationEnvironment appEnv = mainProv.GetService<IApplicationEnvironment>();
IRuntimeEnvironment runtimeEnv = mainProv.GetService<IRuntimeEnvironment>();
ILoggerFactory logFactory = new LoggerFactory();
logFactory.AddConsole(LogLevel.Information);
ServiceCollection sc = new ServiceCollection();
sc.AddInstance(logFactory);
sc.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
sc.AddEntityFramework()
.AddSqlite()
.AddDbContext<StarDbContext>();
sc.AddSingleton<ILibraryManager, LibraryManager>(factory => mainProv.GetService<ILibraryManager>() as LibraryManager);
sc.AddSingleton<ICache, Cache>(factory => new Cache(new CacheContextAccessor()));
sc.AddSingleton<IExtensionAssemblyLoader, ExtensionAssemblyLoader>();
sc.AddSingleton<IStarLibraryManager, StarLibraryManager>();
sc.AddSingleton<PluginLoader>();
sc.AddSingleton(factory => mainProv.GetService<IAssemblyLoadContextAccessor>());
sc.AddInstance(appEnv);
sc.AddInstance(runtimeEnv);
Services = sc;
ServiceProvider = sc.BuildServiceProvider();
}
示例11: DefineServices
public IServiceCollection DefineServices()
{
var services = new ServiceCollection();
services.AddSingleton<ICall, CallOne>();
services.AddScoped<ICall, CallTwo>();
services.AddTransient<ICall, CallThree>();
return services;
}
示例12: GetDefaultServices
public static IServiceCollection GetDefaultServices()
{
var services = new ServiceCollection();
//
// Broker
//
//yield return describe.Singleton<IChannelSender, RemoteStreamMessagePublisher>();
services.AddSingleton<IChannelSender, WebSocketChannelSender>();
//
// Connection
//
//yield return describe.Singleton<IStreamProxy, DefaultStreamProxy>();
services.AddSingleton<IStreamHubProxyFactory, SignalrStreamHubProxyFactory>();
return services;
}
示例13: VerifyAccountControllerSignIn
public async Task VerifyAccountControllerSignIn(bool isPersistent)
{
var app = new ApplicationBuilder(CallContextServiceLocator.Locator.ServiceProvider);
app.UseCookieAuthentication();
var context = new Mock<HttpContext>();
var auth = new Mock<AuthenticationManager>();
context.Setup(c => c.Authentication).Returns(auth.Object).Verifiable();
auth.Setup(a => a.SignInAsync(new IdentityCookieOptions().ApplicationCookieAuthenticationScheme,
It.IsAny<ClaimsPrincipal>(),
It.IsAny<AuthenticationProperties>())).Returns(Task.FromResult(0)).Verifiable();
// REVIEW: is persistant mocking broken
//It.Is<AuthenticationProperties>(v => v.IsPersistent == isPersistent))).Returns(Task.FromResult(0)).Verifiable();
var contextAccessor = new Mock<IHttpContextAccessor>();
contextAccessor.Setup(a => a.HttpContext).Returns(context.Object);
var services = new ServiceCollection();
services.AddLogging();
services.AddInstance(contextAccessor.Object);
services.AddIdentity<TestUser, TestRole>();
services.AddSingleton<IUserStore<TestUser>, InMemoryUserStore<TestUser>>();
services.AddSingleton<IRoleStore<TestRole>, InMemoryRoleStore<TestRole>>();
app.ApplicationServices = services.BuildServiceProvider();
// Act
var user = new TestUser
{
UserName = "Yolo"
};
const string password = "[email protected]!";
var userManager = app.ApplicationServices.GetRequiredService<UserManager<TestUser>>();
var signInManager = app.ApplicationServices.GetRequiredService<SignInManager<TestUser>>();
IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user, password));
var result = await signInManager.PasswordSignInAsync(user, password, isPersistent, false);
// Assert
Assert.True(result.Succeeded);
context.VerifyAll();
auth.VerifyAll();
contextAccessor.VerifyAll();
}
示例14: GetLocalAgentServices
public static IServiceCollection GetLocalAgentServices()
{
var services = new ServiceCollection();
//
// Broker
//
services.AddSingleton<IChannelSender, InProcessChannel>();
return services;
}
示例15: GetDefaultServices
public static IServiceCollection GetDefaultServices()
{
var services = new ServiceCollection();
//
// Broker
//
services.AddSingleton<IAgentBroker, DefaultAgentBroker>();
return services;
}