本文整理汇总了C#中IServiceCollection.TryAddSingleton方法的典型用法代码示例。如果您正苦于以下问题:C# IServiceCollection.TryAddSingleton方法的具体用法?C# IServiceCollection.TryAddSingleton怎么用?C# IServiceCollection.TryAddSingleton使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IServiceCollection
的用法示例。
在下文中一共展示了IServiceCollection.TryAddSingleton方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ConfigureServices
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddMvc(options =>
{
options.Filters.Add(new PayloadValidationFilter());
options.Filters.Add(new RequiredPayloadFilter());
})
.SetHypermediaApiFormatters();
services.AddTransient<Microsoft.IdentityModel.Tokens.ISecurityTokenValidator, SeedTokenValidator>();
services.AddLinkHelper<SeedLinkHelper>();
}
示例2: ConfigureApi
public static new IServiceCollection ConfigureApi(Type apiType, IServiceCollection services)
{
var i = 0;
services.AddService<ISomeService>((sp, next) => new SomeService
{
Inner = next,
Value = i++
})
.AddService<ISomeService>((sp, next) => new SomeService
{
Inner = next,
Value = i++
})
.AddService<ISomeService>((sp, next) => new SomeService
{
Inner = next,
Value = i++
})
.AddService<ISomeService>((sp, next) => new SomeService
{
Inner = next,
Value = i++
})
.AddService<ISomeService, SomeService>();
services.AddScoped(apiType, apiType)
.AddScoped(typeof(ApiBase), apiType)
.AddScoped<ApiContext>();
services.TryAddSingleton<ApiConfiguration>();
return services;
}
示例3: ConfigureServices
public override void ConfigureServices(IServiceCollection serviceCollection)
{
/// Adds the default token providers used to generate tokens for reset passwords, change email
/// and change telephone number operations, and for two factor authentication token generation.
new IdentityBuilder(typeof(User), typeof(Role), serviceCollection).AddDefaultTokenProviders();
// Identity services
serviceCollection.TryAddSingleton<IdentityMarkerService>();
serviceCollection.TryAddScoped<IUserValidator<User>, UserValidator<User>>();
serviceCollection.TryAddScoped<IPasswordValidator<User>, PasswordValidator<User>>();
serviceCollection.TryAddScoped<IPasswordHasher<User>, PasswordHasher<User>>();
serviceCollection.TryAddScoped<ILookupNormalizer, UpperInvariantLookupNormalizer>();
// No interface for the error describer so we can add errors without rev'ing the interface
serviceCollection.TryAddScoped<IdentityErrorDescriber>();
serviceCollection.TryAddScoped<ISecurityStampValidator, SecurityStampValidator<User>>();
serviceCollection.TryAddScoped<IUserClaimsPrincipalFactory<User>, UserClaimsPrincipalFactory<User, Role>>();
serviceCollection.TryAddScoped<UserManager<User>>();
serviceCollection.TryAddScoped<SignInManager<User>>();
serviceCollection.TryAddScoped<IUserStore<User>, UserStore>();
serviceCollection.Configure<IdentityOptions>(options =>
{
options.Cookies.ApplicationCookie.CookieName = "orchauth_" + _tenantName;
options.Cookies.ApplicationCookie.CookiePath = _tenantPrefix;
options.Cookies.ApplicationCookie.LoginPath = new PathString("/Orchard.Users/Account/Login/");
options.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/Orchard.Users/Account/Login/");
});
serviceCollection.AddScoped<UserIndexProvider>();
}
示例4: AddRazorViewEngineServices
// Internal for testing.
internal static void AddRazorViewEngineServices(IServiceCollection services)
{
services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<MvcViewOptions>, MvcRazorMvcViewOptionsSetup>());
services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<RazorViewEngineOptions>, RazorViewEngineOptionsSetup>());
// Caches view locations that are valid for the lifetime of the application.
services.TryAddSingleton<IViewLocationCache, DefaultViewLocationCache>();
services.TryAdd(ServiceDescriptor.Singleton<IChunkTreeCache>(serviceProvider =>
{
var cachedFileProvider = serviceProvider.GetRequiredService<IOptions<RazorViewEngineOptions>>();
return new DefaultChunkTreeCache(cachedFileProvider.Options.FileProvider);
}));
// The host is designed to be discarded after consumption and is very inexpensive to initialize.
services.TryAddTransient<IMvcRazorHost, MvcRazorHost>();
// Caches compilation artifacts across the lifetime of the application.
services.TryAddSingleton<ICompilerCache, CompilerCache>();
// This caches compilation related details that are valid across the lifetime of the application
// and is required to be a singleton.
services.TryAddSingleton<ICompilationService, RoslynCompilationService>();
// Both the compiler cache and roslyn compilation service hold on the compilation related
// caches. RazorCompilation service is just an adapter service, and it is transient to ensure
// the IMvcRazorHost dependency does not maintain state.
services.TryAddTransient<IRazorCompilationService, RazorCompilationService>();
// The ViewStartProvider needs to be able to consume scoped instances of IRazorPageFactory
services.TryAddScoped<IViewStartProvider, ViewStartProvider>();
services.TryAddTransient<IRazorViewFactory, RazorViewFactory>();
services.TryAddSingleton<IRazorPageActivator, RazorPageActivator>();
// Virtual path view factory needs to stay scoped so views can get get scoped services.
services.TryAddScoped<IRazorPageFactory, VirtualPathRazorPageFactory>();
// Only want one ITagHelperActivator so it can cache Type activation information. Types won't conflict.
services.TryAddSingleton<ITagHelperActivator, DefaultTagHelperActivator>();
// Consumed by the Cache tag helper to cache results across the lifetime of the application.
services.TryAddSingleton<IMemoryCache, MemoryCache>();
}
示例5: ConfigureMvc
private static void ConfigureMvc(IServiceCollection services, IIocResolver iocResolver)
{
//See https://github.com/aspnet/Mvc/issues/3936 to know why we added these services.
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
//Use DI to create controllers
services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
//Add feature providers
var partManager = services.GetSingletonServiceOrNull<ApplicationPartManager>();
partManager.FeatureProviders.Add(new AbpAppServiceControllerFeatureProvider(iocResolver));
//Configure JSON serializer
services.Configure<MvcJsonOptions>(jsonOptions =>
{
jsonOptions.SerializerSettings.Converters.Insert(0, new AbpDateTimeConverter());
});
}
示例6: AddViewServices
// Internal for testing.
internal static void AddViewServices(IServiceCollection services)
{
services.AddDataProtection();
services.AddAntiforgery();
services.AddWebEncoders();
services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<MvcViewOptions>, MvcViewOptionsSetup>());
//
// View Engine and related infrastructure
//
// The provider is inexpensive to initialize and provides ViewEngines that may require request
// specific services.
services.TryAddScoped<ICompositeViewEngine, CompositeViewEngine>();
// Support for activating ViewDataDictionary
services.TryAddEnumerable(
ServiceDescriptor
.Transient<IControllerPropertyActivator, ViewDataDictionaryControllerPropertyActivator>());
//
// HTML Helper
//
services.TryAddTransient<IHtmlHelper, HtmlHelper>();
services.TryAddTransient(typeof(IHtmlHelper<>), typeof(HtmlHelper<>));
// DefaultHtmlGenerator is pretty much stateless but depends on IUrlHelper, which is scoped.
// Therefore it too is scoped.
services.TryAddScoped<IHtmlGenerator, DefaultHtmlGenerator>();
//
// JSON Helper
//
services.TryAddSingleton<IJsonHelper, JsonHelper>();
services.TryAdd(ServiceDescriptor.Singleton<JsonOutputFormatter>(serviceProvider =>
{
var options = serviceProvider.GetRequiredService<IOptions<MvcJsonOptions>>().Options;
return new JsonOutputFormatter(options.SerializerSettings);
}));
//
// View Components
//
// These do caching so they should stay singleton
services.TryAddSingleton<IViewComponentSelector, DefaultViewComponentSelector>();
services.TryAddSingleton<IViewComponentActivator, DefaultViewComponentActivator>();
services.TryAddSingleton<
IViewComponentDescriptorCollectionProvider,
DefaultViewComponentDescriptorCollectionProvider>();
services.TryAddTransient<IViewComponentDescriptorProvider, DefaultViewComponentDescriptorProvider>();
services.TryAddSingleton<IViewComponentInvokerFactory, DefaultViewComponentInvokerFactory>();
services.TryAddTransient<IViewComponentHelper, DefaultViewComponentHelper>();
}
示例7: ConfigureApi
public static new IServiceCollection ConfigureApi(Type apiType, IServiceCollection services)
{
var service = new TestSingleCallModelBuilder();
services.AddService<IModelBuilder>((sp, next) => service);
services.AddScoped(apiType, apiType)
.AddScoped(typeof(ApiBase), apiType)
.AddScoped<ApiContext>();
services.TryAddSingleton<ApiConfiguration>();
return services;
}
示例8: ConfigureApi
public static new IServiceCollection ConfigureApi(Type apiType, IServiceCollection services)
{
services.AddScoped(apiType, apiType)
.AddScoped(typeof(ApiBase), apiType)
.AddScoped<ApiContext>();
services.TryAddSingleton<ApiConfiguration>();
services.AddService<IServiceA>((sp, next) => ApiService);
return services;
}
示例9: AddDataAnnotationsServices
// Internal for testing.
internal static void AddDataAnnotationsServices(IServiceCollection services)
{
services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<MvcOptions>, MvcDataAnnotationsMvcOptionsSetup>());
services.TryAddSingleton<IValidationAttributeAdapterProvider, ValidationAttributeAdapterProvider>();
}
示例10: AddMvcCoreServices
// To enable unit testing
internal static void AddMvcCoreServices(IServiceCollection services)
{
//
// Options
//
services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<MvcOptions>, MvcCoreMvcOptionsSetup>());
services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<RouteOptions>, MvcCoreRouteOptionsSetup>());
//
// Action Discovery
//
// These are consumed only when creating action descriptors, then they can be de-allocated
services.TryAddTransient<IAssemblyProvider, DefaultAssemblyProvider>();
services.TryAddTransient<IControllerTypeProvider, DefaultControllerTypeProvider>();
services.TryAddEnumerable(
ServiceDescriptor.Transient<IApplicationModelProvider, DefaultApplicationModelProvider>());
services.TryAddEnumerable(
ServiceDescriptor.Transient<IActionDescriptorProvider, ControllerActionDescriptorProvider>());
services.TryAddSingleton<IActionDescriptorsCollectionProvider, DefaultActionDescriptorsCollectionProvider>();
//
// Action Selection
//
services.TryAddSingleton<IActionSelector, DefaultActionSelector>();
// Performs caching
services.TryAddSingleton<IActionSelectorDecisionTreeProvider, ActionSelectorDecisionTreeProvider>();
// Will be cached by the DefaultActionSelector
services.TryAddEnumerable(
ServiceDescriptor.Transient<IActionConstraintProvider, DefaultActionConstraintProvider>());
//
// Controller Factory
//
// This has a cache, so it needs to be a singleton
services.TryAddSingleton<IControllerFactory, DefaultControllerFactory>();
// Will be cached by the DefaultControllerFactory
services.TryAddTransient<IControllerActivator, DefaultControllerActivator>();
services.TryAddEnumerable(
ServiceDescriptor.Transient<IControllerPropertyActivator, DefaultControllerPropertyActivator>());
//
// Action Invoker
//
// These two access per-request services
services.TryAddTransient<IActionInvokerFactory, ActionInvokerFactory>();
services.TryAddEnumerable(
ServiceDescriptor.Transient<IActionInvokerProvider, ControllerActionInvokerProvider>());
// These are stateless
services.TryAddSingleton<IControllerActionArgumentBinder, DefaultControllerActionArgumentBinder>();
services.TryAddEnumerable(
ServiceDescriptor.Singleton<IFilterProvider, DefaultFilterProvider>());
//
// ModelBinding, Validation and Formatting
//
// The DefaultModelMetadataProvider does significant caching and should be a singleton.
services.TryAddSingleton<IModelMetadataProvider, DefaultModelMetadataProvider>();
services.TryAdd(ServiceDescriptor.Transient<ICompositeMetadataDetailsProvider>(serviceProvider =>
{
var options = serviceProvider.GetRequiredService<IOptions<MvcOptions>>().Options;
return new DefaultCompositeMetadataDetailsProvider(options.ModelMetadataDetailsProviders);
}));
services.TryAdd(ServiceDescriptor.Singleton<IObjectModelValidator>(serviceProvider =>
{
var options = serviceProvider.GetRequiredService<IOptions<MvcOptions>>().Options;
var modelMetadataProvider = serviceProvider.GetRequiredService<IModelMetadataProvider>();
return new DefaultObjectValidator(options.ValidationExcludeFilters, modelMetadataProvider);
}));
//
// Temp Data
//
// Holds per-request data so it should be scoped
services.TryAddScoped<ITempDataDictionary, TempDataDictionary>();
// This does caching so it should stay singleton
services.TryAddSingleton<ITempDataProvider, SessionStateTempDataProvider>();
//
// Random Infrastructure
//
services.TryAddSingleton<MvcMarkerService, MvcMarkerService>();
services.TryAddSingleton<ITypeActivatorCache, DefaultTypeActivatorCache>();
services.TryAddScoped(typeof(IScopedInstance<>), typeof(ScopedInstance<>));
services.TryAddScoped<IUrlHelper, UrlHelper>();
}
示例11: RegisterDependencies
private IServiceProvider RegisterDependencies(IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
var builder = new ContainerBuilder();
// Messaging
if (Environment.IsDevelopment())
{
builder.RegisterType<LocalEmailService>().AsImplementedInterfaces();
}
else
{
builder.RegisterType<MailGunEmailService>().AsImplementedInterfaces();
}
//builder.RegisterType<OopsExceptionHandler>().As<IExceptionHandler>();
builder.RegisterType<ImperaContext>().As<DbContext>().AsSelf(); //.InstancePerLifetimeScope();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>();
builder.RegisterType<DbSeed>().AsSelf();
// Register repositories
//builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(GameRepository)))
// .Where(x => x.Name.EndsWith("Repository") && !x.IsInterface).As(x => x.GetInterfaces());
builder.RegisterType<UserProvider>().As<IUserProvider>();
// Register SignalR hubs
//builder.RegisterHubs(Assembly.GetExecutingAssembly());
// Register Domain services
builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(IGameRepository)))
.Where(x => x.Name.EndsWith("Service") && !x.IsInterface).As(x => x.GetInterfaces());
// Notification
builder.RegisterType<GamePushNotificationService>().AsImplementedInterfaces();
builder.RegisterType<UserPushNotificationService>().AsImplementedInterfaces();
var jsonSettings = new JsonSerializerSettings()
{
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
ContractResolver = new SignalRContractResolver()
};
jsonSettings.Converters.Add(new StringEnumConverter
{
CamelCaseText = false,
AllowIntegerValues = false
});
builder.RegisterInstance(JsonSerializer.Create(jsonSettings)).As<JsonSerializer>();
builder.RegisterModule<Application.DependencyInjectionModule>();
builder.RegisterModule<Domain.DependencyInjectionModule>();
builder.RegisterType<BackgroundJobClient>().AsImplementedInterfaces();
/*
builder.Register(context => this.HubConfiguration.Resolver
.Resolve<Microsoft.AspNet.SignalR.Infrastructure.IConnectionManager>()
.GetHubContext<INotificationHubContext>("notification"))
.As<IHubContext<INotificationHubContext>>();
*/
builder.Populate(services);
IContainer container = null;
container = builder.Build();
return container.Resolve<IServiceProvider>();
}
示例12: AddJsonFormatterServices
// Internal for testing.
internal static void AddJsonFormatterServices(IServiceCollection services)
{
services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<MvcOptions>, MvcJsonMvcOptionsSetup>());
services.TryAddSingleton<JsonResultExecutor>();
}
示例13: RegisterTypes
//internal static void Configure(IApplicationBuilder app)
//{
// //IContainer container = null;
// //var builder = new ContainerBuilder();
// //builder.RegisterApiControllers( Assembly.GetExecutingAssembly() ).InstancePerRequest();
// //builder.RegisterWebApiFilterProvider( config );
// //RegisterTypes( builder );
// //RegisterDrum( config, builder );
// //container = builder.Build();
// //config.DependencyResolver = new AutofacWebApiDependencyResolver( container );
// //app.UseAutofacMiddleware( container );
// //app.UseAutofacWebApi( config );
// //app.UseWebApi( config );
//}
//private static void RegisterDrum( HttpConfiguration config, ContainerBuilder builder )
//{
// // Web API routes
// UriMakerContext uriMakerContext = config.MapHttpAttributeRoutesAndUseUriMaker();
// builder.RegisterInstance( uriMakerContext ).ExternallyOwned();
// builder.RegisterHttpRequestMessage( config );
// builder.RegisterGeneric( typeof( UriMaker<> ) ).AsSelf().InstancePerRequest();
// builder.RegisterType<DrumUrlProvider>().As<IUrlProvider>();
//}
public static void RegisterTypes( IServiceCollection services)
{
services.TryAddSingleton<IBookService, BookService>();
services.TryAddSingleton<IAuthorService, AuthorService>();
services.TryAddSingleton<ILendingService, LendingService>();
//builder.RegisterType<BookService>().As<IBookService>();
//builder.RegisterType<AuthorService>().As<IAuthorService>();
//builder.RegisterType<LendingService>().As<ILendingService>();
services.TryAddSingleton<BookResourceAssembler>();
services.TryAddSingleton<AuthorResourceAssembler>();
services.TryAddSingleton<LendingRecordResourceAssembler>();
//builder.RegisterType<BookResourceAssembler>().AsSelf().PropertiesAutowired( PropertyWiringOptions.AllowCircularDependencies );
//builder.RegisterType<AuthorResourceAssembler>().AsSelf().PropertiesAutowired( PropertyWiringOptions.AllowCircularDependencies );
//builder.RegisterType<LendingRecordResourceAssembler>().AsSelf();
services.TryAddSingleton<IAuthorStore, AuthorDocumentStore>();
services.TryAddSingleton<IBookStorage, BookDocumentStore>();
services.TryAddSingleton<ILendingRecordStore, LendingRecordDocumentStore>();
//builder.RegisterType<AuthorDocumentStore>().As<IAuthorStore>();
//builder.RegisterType<BookDocumentStore>().As<IBookStorage>();
//builder.RegisterType<LendingRecordDocumentStore>().As<ILendingRecordStore>();
services.TryAddSingleton<IAuthorRepository, AuthorRepository>();
services.TryAddSingleton<IISBNLookupService,ISBNDBLookupService>();
//builder.RegisterType<AuthorRepository>().As<IAuthorRepository>();
//builder.RegisterType<ISBNDBLookupService>().As<IISBNLookupService>();
services.AddSingleton((sp) => DocumentStoreIndex.BookStore);
services.AddSingleton((sp) => DocumentStoreIndex.AuthorStore);
services.AddSingleton((sp) => DocumentStoreIndex.LendingRecordStore);
//builder.RegisterInstance( DocumentStoreIndex.BookStore ).As<IDocumentStore<Book>>();
//builder.RegisterInstance( DocumentStoreIndex.AuthorStore ).As<IDocumentStore<Author>>();
//builder.RegisterInstance( DocumentStoreIndex.LendingRecordStore ).As<IDocumentStore<LendingRecord>>();
}
示例14: AddFormatterMappingsServices
// Internal for testing.
internal static void AddFormatterMappingsServices(IServiceCollection services)
{
services.TryAddSingleton<FormatFilter, FormatFilter>();
}
示例15: PrepareRouteServices
private static void PrepareRouteServices(IServiceCollection serviceCollection)
{
var modelBindingActionInvokerFactoryType = typeof(IModelBindingActionInvokerFactory);
if (serviceCollection.All(s => s.ServiceType != modelBindingActionInvokerFactoryType))
{
serviceCollection.TryAddEnumerable(
ServiceDescriptor.Transient<IActionInvokerProvider, ModelBindingActionInvokerProvider>());
serviceCollection.TryAddSingleton(modelBindingActionInvokerFactoryType, typeof(ModelBindingActionInvokerFactory));
}
routeServiceProvider = serviceCollection.BuildServiceProvider();
serviceCollection.RemoveSingleton(modelBindingActionInvokerFactoryType);
var actionInvokerProviders = serviceCollection.Where(s => s.ServiceType == typeof(IActionInvokerProvider)).ToList();
if (actionInvokerProviders.Count > 1)
{
serviceCollection.Remove(actionInvokerProviders.LastOrDefault());
}
}