本文整理汇总了C#中IServiceCollection.AddSingleton方法的典型用法代码示例。如果您正苦于以下问题:C# IServiceCollection.AddSingleton方法的具体用法?C# IServiceCollection.AddSingleton怎么用?C# IServiceCollection.AddSingleton使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IServiceCollection
的用法示例。
在下文中一共展示了IServiceCollection.AddSingleton方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ConfigureServices
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddCaching();
services.AddSession();
services.AddMvc();
services.AddSingleton<PassThroughAttribute>();
services.AddSingleton<UserNameService>();
services.AddTransient<ITestService, TestService>();
services.ConfigureMvc(options =>
{
options.Filters.Add(typeof(PassThroughAttribute), order: 17);
options.AddXmlDataContractSerializerFormatter();
options.Filters.Add(new FormatFilterAttribute());
});
#if DNX451
// Fully-qualify configuration path to avoid issues in functional tests. Just "config.json" would be fine
// but Configuration uses CallContextServiceLocator.Locator.ServiceProvider to get IApplicationEnvironment.
// Functional tests update that service but not in the static provider.
var applicationEnvironment = services.BuildServiceProvider().GetRequiredService<IApplicationEnvironment>();
var configurationPath = Path.Combine(applicationEnvironment.ApplicationBasePath, "config.json");
// Set up configuration sources.
var configuration = new Configuration()
.AddJsonFile(configurationPath)
.AddEnvironmentVariables();
string diSystem;
if (configuration.TryGet("DependencyInjection", out diSystem) &&
diSystem.Equals("AutoFac", StringComparison.OrdinalIgnoreCase))
{
_autoFac = true;
services.ConfigureRazorViewEngine(options =>
{
var expander = new LanguageViewLocationExpander(
context => context.HttpContext.Request.Query["language"]);
options.ViewLocationExpanders.Insert(0, expander);
});
// Create the autofac container
var builder = new ContainerBuilder();
// Create the container and use the default application services as a fallback
AutofacRegistration.Populate(
builder,
services);
builder.RegisterModule<MonitoringModule>();
var container = builder.Build();
return container.Resolve<IServiceProvider>();
}
else
#endif
{
return services.BuildServiceProvider();
}
}
示例2: ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
//try
//{
// var connectionString = Configuration["database:connection"];
// System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connectionString);
// conn.Open();
// conn.Close();
//}
//catch (System.Exception ex)
//{
// throw;
//}
services.AddMvc();
services.AddDbContext<OdeToFoodDbContext>(options => options.UseSqlServer(Configuration["database:connection"]));
services.AddSingleton(provider => Configuration);
services.AddSingleton<IGreeter, Greeter>();
//services.AddScoped<IRestaurantData, InMemoryRestaurantData>();
services.AddScoped<IRestaurantData, SqlRestaurantData>();
}
示例3: ConfigureServices
// This method gets called by a runtime.
// Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
var jsonFormatter = (JsonOutputFormatter)(options.OutputFormatters
.First(formatter => formatter.Instance is JsonOutputFormatter)
.Instance);
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
//options.Filters.Add(new RequireHttpsAttribute());
});
services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
services.AddTransient<ILinkHelper, LinkHelper>();
services.AddScoped<ISecurityHelper, SecurityHelper>();
services.AddSingleton <IWebJobController, WebJobController>();
services.AddSingleton<IVolatileStorageController, VolatileStorageController>();
services.AddSingleton<IGraphAPIProvider, GraphAPIProvider>();
services.AddInstance(Configuration);
services.AddDocumentDbRepositories(Configuration);
services.AddKeyVaultRepositories(Configuration);
}
示例4: ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<IConnectionStringParser, ConnectionStringParser>();
services.AddSingleton<IMonitor, DatabaseMonitor>();
services.AddSingleton<IConfiguration>(provider => _configuration);
}
示例5: ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddCaching();
services.AddSession();
// Configuration
services.Configure<EncryptionConfig>(Configuration.GetSection("Encryption"));
services.Configure<EmailConfig>(Configuration.GetSection("Email"));
services.Configure<RedisConfig>(Configuration.GetSection("Redis"));
// Dependency Injection
services.AddSingleton<IRedisService, RedisService>();
services.AddSingleton<IEncryptionService, BasicEncryption>();
services.AddSingleton<ISchedulerService, SchedulerService>();
services.AddSingleton<IEmailService, EmailService>();
services.AddTransient<IMojangService, MojangService>();
services.AddTransient<IUserService, UserService>();
services.AddTransient<IUsernameService, UsernameService>();
// Automapper
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new AutoMapperProfile());
});
services.AddSingleton(sp => config.CreateMapper());
}
示例6: ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddLogging();
services.AddSingleton<FabricClient>();
services.AddSingleton<Resolver>();
services.AddMvc();
}
示例7: ConfigureServices
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton(x => Configuration);
services.AddSingleton(typeof (IGreetingService), typeof (GreetingService));
}
示例8: ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddSingleton<ITodoRepository, TodoRepository>();
services.AddSingleton<TaskManagerRepository>();
}
示例9: ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddIdentity<ApplicationUser, IdentityRole>(o =>
{
o.Password.RequireDigit = false;
o.Password.RequiredLength = 6;
o.Password.RequireLowercase = false;
o.Password.RequireNonLetterOrDigit = false;
o.Password.RequireUppercase = false;
o.User.RequireUniqueEmail = true;
o.User.AllowedUserNameCharacters = null;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new
CamelCasePropertyNamesContractResolver();
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddSingleton<ExcelManager>();
services.AddSingleton((e) => Configuration);
}
示例10: ConfigureServices
// Set up application services
public void ConfigureServices(IServiceCollection services)
{
// Add MVC services to the services container
services.AddMvc();
services.AddSingleton<ICompilerCache, CustomCompilerCache>();
services.AddSingleton<CompilerCacheInitialiedService>();
}
示例11: ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
// Get the configuration info
j64HarmonyGateway j64Config = j64HarmonyGatewayRepository.Read();
services.AddSingleton<j64HarmonyGateway>(j64Config);
// Get an auth token from the harmony "cloud"
Hub myHub = new Hub();
bool connected = myHub.StartNewConnection(j64Config.Email, j64Config.Password, j64Config.HubAddress, j64Config.HubPort);
// Add the hub as a service available to all of the controllers
services.AddSingleton<Hub>(myHub);
}
示例12: ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.AddSingleton<IConfigurationRoot>(Configuration);
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAuthentication(Configuration);
services.Configure<PayPalClientSettings>(Configuration.GetSection("PayPalClientSettings"));
services.AddSingleton<PayPalClient>();
services.AddLogging();
services.AddMvc();
// register document store
var store = DocumentStore.For(_ =>
{
_.AutoCreateSchemaObjects = AutoCreate.CreateOrUpdate;
_.Connection(Configuration.GetConnectionString("HopeNB"));
AsyncSessionFactory.Register(_);
});
store.Schema.ApplyAllConfiguredChangesToDatabase();
services.AddSingleton<IDocumentStore>(store);
AsyncSessionFactory.DocumentStore = store;
services.AddDistributedMemoryCache();
services.AddMultitenancy<Organization, CachingOrganizationResolver>();
}
示例13: ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var connectionString = Configuration["db:bstu-mssql"];
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<DataContext>(options => options.UseSqlServer(connectionString));
services.AddScoped<IDataContext>(provider => provider.GetService<DataContext>());
services.AddScoped<INewsRepository, NewsRepository>();
services.AddScoped<IFeedNewsService, FeedNewsService>();
services.AddScoped<IUpcomingNewsService, UpcomingNewsService>();
services.Configure<FileSystem>(options =>
{
options.ThumbsPath = Configuration["fs:thumbs-path"];
options.ThumbsFilename = Configuration["fs:thumbs-filename"];
});
if (Configuration["env"] == "dev")
{
//services.AddSingleton<IImageRepository, HttpImageRepository>();
services.AddSingleton<IImageRepository, DirectImageRepository>();
}
else
{
services.AddSingleton<IImageRepository, FileImageRepository>();
}
services.AddSingleton<IImageCache, ImageCache>();
services.AddSingleton<IImageService, ImageService>();
}
示例14: ConfigureServices
// This method gets called by a runtime.
// Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
// Add Application Insights data collection services to the services container.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
// Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers.
// You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json.
// services.AddWebApiConventions();
var hosts = new MaxWeightHashing<RemoteHost>("FIXME-uniquekeyfromconfig");
RemoteHost localHost = new RemoteHost {Uri = new Uri("http://localhost:35358")};
services.AddSingleton<RemoteHost>(x => localHost);
hosts.Add("localhost", localHost);
// Use memory only stable store if none other is available. FUTURE -- use azure SQL or tables
services.AddSingleton<IStableStore, MemoryOnlyStableStore>();
var options = new BlockingAlgorithmOptions();
services.AddSingleton<BlockingAlgorithmOptions>(x => options);
services.AddSingleton<BlockingAlgorithmOptions>(x => options);
services.AddSingleton<MemoryUsageLimiter, MemoryUsageLimiter>();
services.AddSingleton<IDistributedResponsibilitySet<RemoteHost>>(x => hosts);
services.AddSingleton<UserAccountClient>();
services.AddSingleton<LoginAttemptClient>();
services.AddSingleton<UserAccountController>();
services.AddSingleton<LoginAttemptController>();
}
示例15: ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// 리포지터리 등록
// 샘플이라 단순한 in-memory static 저장소를 사용합니다.
services.AddSingleton<CheckoutRepository>();
services.AddSingleton<PaymentRepository>();
// 아임포트 서비스 등록
services.AddSingleton(serviceProvider =>
{
var options =
serviceProvider
.GetService<IOptions<IamportHttpClientOptions>>();
return options.Value;
});
services.AddSingleton<IIamportClient, IamportHttpClient>();
services.AddSingleton<IPaymentsApi, PaymentsApi>();
services.Configure<IamportHttpClientOptions>(
Configuration.GetSection("iamport"));
// Add framework services.
services.AddMvc();
// 다음 설정을 하지 않으면 View 렌더링시 Unicode 문자열이 Ӓ 형식으로 출력됩니다.
services.Configure<WebEncoderOptions>(options =>
{
options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);
});
}