本文整理汇总了C#中IServiceCollection.TryAddScoped方法的典型用法代码示例。如果您正苦于以下问题:C# IServiceCollection.TryAddScoped方法的具体用法?C# IServiceCollection.TryAddScoped怎么用?C# IServiceCollection.TryAddScoped使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IServiceCollection
的用法示例。
在下文中一共展示了IServiceCollection.TryAddScoped方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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>();
}
示例2: ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// you can use either json or xml to maintain your navigation map we provide examples of each navigation.xml and
// navigation.json in the root of this project
// you can override the name of the file used with AppSettings:NavigationXmlFileName or AppSettings:NavigationJsonFileName in config.json
// the file must live in the root of the web project code not in wwwroot
// it is arguable which is easier for humans to read and maintain, myself I think for something like a navigation tree
// that could get large xml is easier to work with and not make mistakes. in json one missing or extra comma can break it
// granted xml can be broken by typos too but the end tags make it easier to keep track of where you are imho (JA)
//services.TryAddScoped<INavigationTreeBuilder, JsonNavigationTreeBuilder>();
//services.TryAddScoped<INavigationTreeBuilder, HardCodedNavigationTreeBuilder>();
services.TryAddScoped<INavigationTreeBuilder, XmlNavigationTreeBuilder>();
services.TryAddScoped<INodeUrlPrefixProvider, DefaultNodeUrlPrefixProvider>();
services.TryAddScoped<INavigationNodePermissionResolver, NavigationNodePermissionResolver>();
services.Configure<NavigationOptions>(Configuration.GetSection("NavigationOptions"));
services.Configure<DistributedCacheNavigationTreeBuilderOptions>(Configuration.GetSection("DistributedCacheNavigationTreeBuilderOptions"));
services.Configure<MemoryCacheNavigationTreeBuilderOptions>(Configuration.GetSection("MemoryCacheNavigationTreeBuilderOptions"));
services.TryAddScoped<INavigationCacheKeyResolver, DefaultNavigationCacheKeyResolver>();
// Add MVC services to the services container.
services.AddMvc();
}
示例3: ConfigureServices
public override void ConfigureServices(IServiceCollection services)
{
services.TryAddScoped<RoleManager<Role>>();
services.TryAddScoped<IRoleStore<Role>, RoleStore>();
services.TryAddScoped<IRoleProvider, RoleStore>();
services.AddScoped<RoleUpdater>();
services.AddScoped<IFeatureEventHandler>(sp => sp.GetRequiredService<RoleUpdater>());
services.AddScoped<IAuthorizationHandler, RolesPermissionsHandler>();
}
示例4: 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>();
}
示例5: 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>();
}
示例6: ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.TryAddScoped<ICoreModelMapper, SqlServerCoreModelMapper>();
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<CoreDbContext>(options =>
options.UseSqlServer(Configuration["Data:EF7ConnectionOptions:ConnectionString"])
);
}
示例7: ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.TryAddScoped<ICoreModelMapper, SqlServerCoreModelMapper>();
services.AddEntityFrameworkSqlServer()
.AddDbContext<CoreDbContext>((serviceProvider, options) =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
.UseInternalServiceProvider(serviceProvider)
);
//services.AddDbContext<CoreDbContext>(options =>
// options.UseSqlServer(Configuration["Data:EF7ConnectionOptions:ConnectionString"])
// );
}
示例8: ConfigureServices
// This method gets called by the runtime. Use this method to add services to the container.
//public IServiceProvider ConfigureServices(IServiceCollection services)
public void ConfigureServices(IServiceCollection services)
{
//http://docs.asp.net/en/latest/security/data-protection/configuration/overview.html
//If you change the key persistence location, the system will no longer automatically encrypt keys
// at rest since it doesn’t know whether DPAPI is an appropriate encryption mechanism.
services.ConfigureDataProtection(configure =>
{
string pathToCryptoKeys = appBasePath + Path.DirectorySeparatorChar
+ "dp_keys" + Path.DirectorySeparatorChar;
// these keys are not encrypted at rest
// since we have specified a non default location
// that also makes the key portable so they will still work if we migrate to
// a new machine (will they work on different OS? I think so)
// this is a similar server migration issue as the old machinekey
// where we specified a machinekey in web.config so it would not change if we
// migrate to a new server
configure.PersistKeysToFileSystem(
new DirectoryInfo(pathToCryptoKeys)
);
//configure.ProtectKeysWithCertificate("thumbprint");
//configure.SetDefaultKeyLifetime(TimeSpan.FromDays(14));
///configure.
});
//services.TryAddScoped<IConfigurationRoot, Configuration>();
//http://blog.getglimpse.com/2015/11/19/installing-glimpse-v2-beta1/
bool enableGlimpse = Configuration.Get<bool>("DiagnosticOptions:EnableGlimpse", false);
if (enableGlimpse)
{
services.AddGlimpse();
}
//services.AddLocalization(options => options.ResourcesPath = "AppResources");
ConfigureAuthPolicy(services);
// we may need this on linux/mac as urls are case sensitive by default
//services.Configure<RouteOptions>(routeOptions => routeOptions.LowercaseUrls = true);
// Setup dependencies for cloudscribe Identity, Roles and and Site Administration
// this is in Startup.CloudscribeCore.DI.MS.cs
services.ConfigureCloudscribeCore(Configuration);
services.TryAddScoped<LogManager, LogManager>();
//services.Configure<MvcOptions>(options =>
//{
// // forces https
// // note that the home or root is still accessible non securely
// // only enable this if you have an ssl certificate installed and working
// //options.Filters.Add(new RequireHttpsAttribute());
// //options.ModelValidatorProviders.Add()
//});
//services.Configure<IdentityOptions>(options =>
//{
// options.Password.RequiredLength
//});
// we are adding this from Startup.CloudscribeCore.cs so it is not needed here
// Add MVC services to the services container.
//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();
//Autofac config
// var builder = new ContainerBuilder();
////Populate the container with services that were previously registered
//// it seems this depends on beta4
//builder.Populate(services);
//var container = builder.Build();
//return container.Resolve<IServiceProvider>();
}
示例9: ConfigureServices
public override void ConfigureServices(IServiceCollection serviceCollection)
{
serviceCollection.TryAddScoped<RoleManager<Role>, RoleManager<Role>>();
serviceCollection.TryAddScoped<IRoleStore<Role>, RoleStore>();
serviceCollection.TryAddScoped<IRoleManager, RoleManager>();
}
示例10: AddViewServices
// Internal for testing.
internal static void AddViewServices(IServiceCollection services)
{
services.AddDataProtection();
services.AddAntiforgery();
services.AddWebEncoders();
services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<MvcViewOptions>, MvcViewOptionsSetup>());
services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<MvcOptions>, TempDataMvcOptionsSetup>());
//
// View Engine and related infrastructure
//
services.TryAddSingleton<ICompositeViewEngine, CompositeViewEngine>();
services.TryAddSingleton<ViewResultExecutor>();
services.TryAddSingleton<PartialViewResultExecutor>();
// Support for activating ViewDataDictionary
services.TryAddEnumerable(
ServiceDescriptor
.Transient<IControllerPropertyActivator, ViewDataDictionaryControllerPropertyActivator>());
//
// HTML Helper
//
services.TryAddTransient<IHtmlHelper, HtmlHelper>();
services.TryAddTransient(typeof(IHtmlHelper<>), typeof(HtmlHelper<>));
services.TryAddSingleton<IHtmlGenerator, DefaultHtmlGenerator>();
//
// JSON Helper
//
services.TryAddSingleton<IJsonHelper, JsonHelper>();
services.TryAdd(ServiceDescriptor.Singleton<JsonOutputFormatter>(serviceProvider =>
{
var options = serviceProvider.GetRequiredService<IOptions<MvcJsonOptions>>().Value;
var charPool = serviceProvider.GetRequiredService<ArrayPool<char>>();
return new JsonOutputFormatter(options.SerializerSettings, charPool);
}));
//
// 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>();
//
// Temp Data
//
// This does caching so it should stay singleton
services.TryAddSingleton<ITempDataProvider, SessionStateTempDataProvider>();
//
// Antiforgery
//
services.TryAddSingleton<ValidateAntiforgeryTokenAuthorizationFilter>();
services.TryAddSingleton<AutoValidateAntiforgeryTokenAuthorizationFilter>();
// These are stateless so their lifetime isn't really important.
services.TryAddSingleton<ITempDataDictionaryFactory, TempDataDictionaryFactory>();
services.TryAddSingleton<SaveTempDataFilter>();
services.TryAddSingleton(ArrayPool<ViewBufferValue>.Shared);
services.TryAddScoped<IViewBufferScope, MemoryPoolViewBufferScope>();
}
示例11: 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>();
}