Exemple #1
0
 /// <summary>
 /// An <see cref="IXmlEncryptor"/> backed by DPAPI.
 /// </summary>
 public static ServiceDescriptor IXmlEncryptor_Dpapi(bool protectToMachine)
 {
     CryptoUtil.AssertPlatformIsWindows();
     return(ServiceDescriptor.Singleton <IXmlEncryptor>(services => new DpapiXmlEncryptor(protectToMachine, services)));
 }
        // To enable unit testing
        internal static void AddMvcCoreServices(IServiceCollection services)
        {
            //
            // Options
            //
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IConfigureOptions <MvcOptions>, MvcCoreMvcOptionsSetup>());
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IPostConfigureOptions <MvcOptions>, MvcOptionsConfigureCompatibilityOptions>());
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IConfigureOptions <ApiBehaviorOptions>, ApiBehaviorOptionsSetup>());
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IConfigureOptions <RouteOptions>, MvcCoreRouteOptionsSetup>());

            //
            // Action Discovery
            //
            // These are consumed only when creating action descriptors, then they can be deallocated

            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IApplicationModelProvider, DefaultApplicationModelProvider>());
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IApplicationModelProvider, ApiBehaviorApplicationModelProvider>());
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IActionDescriptorProvider, ControllerActionDescriptorProvider>());

            services.TryAddSingleton <IActionDescriptorCollectionProvider, ActionDescriptorCollectionProvider>();

            //
            // Action Selection
            //
            services.TryAddSingleton <IActionSelector, ActionSelector>();
            services.TryAddSingleton <ActionConstraintCache>();

            // 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.TryAddSingleton <IControllerFactoryProvider, ControllerFactoryProvider>();
            services.TryAddSingleton <IControllerActivatorProvider, ControllerActivatorProvider>();
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IControllerPropertyActivator, DefaultControllerPropertyActivator>());

            //
            // Action Invoker
            //
            // The IActionInvokerFactory is cachable
            services.TryAddSingleton <IActionInvokerFactory, ActionInvokerFactory>();
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IActionInvokerProvider, ControllerActionInvokerProvider>());

            // These are stateless
            services.TryAddSingleton <ControllerActionInvokerCache>();
            services.TryAddEnumerable(
                ServiceDescriptor.Singleton <IFilterProvider, DefaultFilterProvider>());
            services.TryAddSingleton <IActionResultTypeMapper, ActionResultTypeMapper>();

            //
            // Request body limit filters
            //
            services.TryAddTransient <RequestSizeLimitFilter>();
            services.TryAddTransient <DisableRequestSizeLimitFilter>();
            services.TryAddTransient <RequestFormLimitsFilter>();

            //
            // ModelBinding, Validation
            //
            // The DefaultModelMetadataProvider does significant caching and should be a singleton.
            services.TryAddSingleton <IModelMetadataProvider, DefaultModelMetadataProvider>();
            services.TryAdd(ServiceDescriptor.Transient <ICompositeMetadataDetailsProvider>(s =>
            {
                var options = s.GetRequiredService <IOptions <MvcOptions> >().Value;
                return(new DefaultCompositeMetadataDetailsProvider(options.ModelMetadataDetailsProviders));
            }));
            services.TryAddSingleton <IModelBinderFactory, ModelBinderFactory>();
            services.TryAddSingleton <IObjectModelValidator>(s =>
            {
                var options          = s.GetRequiredService <IOptions <MvcOptions> >().Value;
                var metadataProvider = s.GetRequiredService <IModelMetadataProvider>();
                return(new DefaultObjectValidator(metadataProvider, options.ModelValidatorProviders));
            });
            services.TryAddSingleton <ClientValidatorCache>();
            services.TryAddSingleton <ParameterBinder>();

            //
            // Random Infrastructure
            //
            services.TryAddSingleton <MvcMarkerService, MvcMarkerService>();
            services.TryAddSingleton <ITypeActivatorCache, TypeActivatorCache>();
            services.TryAddSingleton <IUrlHelperFactory, UrlHelperFactory>();
            services.TryAddSingleton <IHttpRequestStreamReaderFactory, MemoryPoolHttpRequestStreamReaderFactory>();
            services.TryAddSingleton <IHttpResponseStreamWriterFactory, MemoryPoolHttpResponseStreamWriterFactory>();
            services.TryAddSingleton(ArrayPool <byte> .Shared);
            services.TryAddSingleton(ArrayPool <char> .Shared);
            services.TryAddSingleton <OutputFormatterSelector, DefaultOutputFormatterSelector>();
            services.TryAddSingleton <IActionResultExecutor <ObjectResult>, ObjectResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <PhysicalFileResult>, PhysicalFileResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <VirtualFileResult>, VirtualFileResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <FileStreamResult>, FileStreamResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <FileContentResult>, FileContentResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <RedirectResult>, RedirectResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <LocalRedirectResult>, LocalRedirectResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <RedirectToActionResult>, RedirectToActionResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <RedirectToRouteResult>, RedirectToRouteResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <RedirectToPageResult>, RedirectToPageResultExecutor>();
            services.TryAddSingleton <IActionResultExecutor <ContentResult>, ContentResultExecutor>();

            //
            // Route Handlers
            //
            services.TryAddSingleton <MvcRouteHandler>();          // Only one per app
            services.TryAddTransient <MvcAttributeRouteHandler>(); // Many per app

            //
            // Dispatching
            //
            services.TryAddEnumerable(
                ServiceDescriptor.Singleton <EndpointDataSource, MvcEndpointDataSource>());
            services.TryAddSingleton <MvcEndpointInvokerFactory>();

            //
            // Middleware pipeline filter related
            //
            services.TryAddSingleton <MiddlewareFilterConfigurationProvider>();
            // This maintains a cache of middleware pipelines, so it needs to be a singleton
            services.TryAddSingleton <MiddlewareFilterBuilder>();
            // Sets ApplicationBuilder on MiddlewareFilterBuilder
            services.TryAddEnumerable(ServiceDescriptor.Singleton <IStartupFilter, MiddlewareFilterBuilderStartupFilter>());
        }
 public static IServiceCollection ReplaceConfiguration(this IServiceCollection services, IConfiguration configuration)
 {
     return(services.Replace(ServiceDescriptor.Singleton <IConfiguration>(configuration)));
 }
Exemple #4
0
 // to enable unit testing
 internal static void AddSqlServerCacheServices(IServiceCollection services)
 {
     services.Add(ServiceDescriptor.Singleton <IDistributedCache, SqlServerCache>());
 }
Exemple #5
0
        // 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>();
            services.TryAddSingleton <ExpressionTextCache>();

            //
            // 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 <IViewComponentFactory, DefaultViewComponentFactory>();
            services.TryAddSingleton <IViewComponentActivator, DefaultViewComponentActivator>();
            services.TryAddSingleton <
                IViewComponentDescriptorCollectionProvider,
                DefaultViewComponentDescriptorCollectionProvider>();

            services.TryAddSingleton <ViewComponentInvokerCache>();
            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>();
        }
Exemple #6
0
        /// <summary>
        /// 添加选项配置
        /// </summary>
        /// <typeparam name="TOptions">选项类型</typeparam>
        /// <param name="services">服务集合</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddConfigurableOptions <TOptions>(this IServiceCollection services)
            where TOptions : class, IConfigurableOptions
        {
            var optionsType     = typeof(TOptions);
            var optionsSettings = optionsType.GetCustomAttribute <OptionsSettingsAttribute>(false);

            // 获取键名
            var jsonKey = GetOptionsJsonKey(optionsSettings, optionsType);

            // 配置选项(含验证信息)
            var configurationRoot    = App.Configuration;
            var optionsConfiguration = configurationRoot.GetSection(jsonKey);

            // 配置选项监听
            if (typeof(IConfigurableOptionsListener <TOptions>).IsAssignableFrom(optionsType))
            {
                var onListenerMethod = optionsType.GetMethod(nameof(IConfigurableOptionsListener <TOptions> .OnListener));
                if (onListenerMethod != null)
                {
                    ChangeToken.OnChange(() => configurationRoot.GetReloadToken(), () =>
                    {
                        var options = optionsConfiguration.Get <TOptions>();
                        onListenerMethod.Invoke(options, new object[] { options, optionsConfiguration });
                    });
                }
            }

            services.AddOptions <TOptions>()
            .Bind(optionsConfiguration, options =>
            {
                options.BindNonPublicProperties = true;     // 绑定私有变量
            })
            .ValidateDataAnnotations();

            // 配置复杂验证后后期配置
            var validateInterface = optionsType.GetInterfaces()
                                    .FirstOrDefault(u => u.IsGenericType && typeof(IConfigurableOptions).IsAssignableFrom(u.GetGenericTypeDefinition()));

            if (validateInterface != null)
            {
                var genericArguments = validateInterface.GenericTypeArguments;

                // 配置复杂验证
                if (genericArguments.Length > 1)
                {
                    services.TryAddEnumerable(ServiceDescriptor.Singleton(typeof(IValidateOptions <TOptions>), genericArguments.Last()));
                }

                // 配置后期配置
                var postConfigureMethod = optionsType.GetMethod(nameof(IConfigurableOptions <TOptions> .PostConfigure));
                if (postConfigureMethod != null)
                {
                    if (optionsSettings?.PostConfigureAll != true)
                    {
                        services.PostConfigure <TOptions>(options => postConfigureMethod.Invoke(options, new object[] { options, optionsConfiguration }));
                    }
                    else
                    {
                        services.PostConfigureAll <TOptions>(options => postConfigureMethod.Invoke(options, new object[] { options, optionsConfiguration }));
                    }
                }
            }

            return(services);
        }
 public static FluentEmailServicesBuilder AddRazorRenderer(this FluentEmailServicesBuilder builder)
 {
     builder.Services.TryAdd(ServiceDescriptor.Singleton <ITemplateRenderer, RazorRenderer>());
     return(builder);
 }
Exemple #8
0
 /// <summary>
 /// An <see cref="ICertificateResolver"/> backed by the default implementation.
 /// </summary>
 public static ServiceDescriptor ICertificateResolver_Default()
 {
     return(ServiceDescriptor.Singleton <ICertificateResolver, CertificateResolver>());
 }
Exemple #9
0
 /// <summary>
 /// An ephemeral <see cref="IDataProtectionProvider"/>.
 /// </summary>
 public static ServiceDescriptor IDataProtectionProvider_Ephemeral()
 {
     return(ServiceDescriptor.Singleton <IDataProtectionProvider>(services => new EphemeralDataProtectionProvider(services)));
 }
Exemple #10
0
 /// <summary>
 /// An <see cref="IXmlRepository"/> backed by the Windows registry.
 /// </summary>
 public static ServiceDescriptor IXmlRepository_Registry(RegistryKey registryKey)
 {
     return(ServiceDescriptor.Singleton <IXmlRepository>(services => new RegistryXmlRepository(registryKey, services)));
 }
Exemple #11
0
 /// <summary>
 /// An <see cref="IAuthenticatedEncryptorConfiguration"/> backed by an <see cref="IInternalAuthenticatedEncryptionSettings"/>.
 /// </summary>
 public static ServiceDescriptor IAuthenticatedEncryptorConfiguration_FromSettings(IInternalAuthenticatedEncryptionSettings options)
 {
     return(ServiceDescriptor.Singleton <IAuthenticatedEncryptorConfiguration>(options.ToConfiguration));
 }
Exemple #12
0
 /// <summary>
 /// An <see cref="IXmlRepository"/> backed by volatile in-process memory.
 /// </summary>
 public static ServiceDescriptor IXmlRepository_InMemory()
 {
     return(ServiceDescriptor.Singleton <IXmlRepository>(services => new EphemeralXmlRepository(services)));
 }
Exemple #13
0
 /// <summary>
 /// An <see cref="IXmlRepository"/> backed by a file system.
 /// </summary>
 public static ServiceDescriptor IXmlRepository_FileSystem(DirectoryInfo directory)
 {
     return(ServiceDescriptor.Singleton <IXmlRepository>(services => new FileSystemXmlRepository(directory, services)));
 }
Exemple #14
0
 /// <summary>
 /// An <see cref="IXmlEncryptor"/> backed by DPAPI-NG.
 /// </summary>
 public static ServiceDescriptor IXmlEncryptor_DpapiNG(string protectionDescriptorRule, DpapiNGProtectionDescriptorFlags flags)
 {
     CryptoUtil.AssertPlatformIsWindows8OrLater();
     return(ServiceDescriptor.Singleton <IXmlEncryptor>(services => new DpapiNGXmlEncryptor(protectionDescriptorRule, flags, services)));
 }
Exemple #15
0
 public static AuthenticationBuilder AddBundleAwareCustomJwtBearer(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action <JwtBearerOptions> configureOptions)
 {
     builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <IPostConfigureOptions <JwtBearerOptions>, JwtBearerPostConfigureOptions>());
     return(builder.AddScheme <JwtBearerOptions, BundleAwareJwtBearerHandler>(authenticationScheme, displayName, configureOptions));
 }
Exemple #16
0
        /// <summary>
        /// Adds services required for routing requests.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection"/> to add the services to.</param>
        /// <returns>The <see cref="IServiceCollection"/> so that additional calls can be chained.</returns>
        public static IServiceCollection AddRouting(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            services.TryAddTransient <IInlineConstraintResolver, DefaultInlineConstraintResolver>();
            services.TryAddSingleton <ObjectPool <UriBuildingContext> >(s =>
            {
                var provider = s.GetRequiredService <ObjectPoolProvider>();
                return(provider.Create <UriBuildingContext>(new UriBuilderContextPooledObjectPolicy()));
            });

            // The TreeRouteBuilder is a builder for creating routes, it should stay transient because it's
            // stateful.
            services.TryAdd(ServiceDescriptor.Transient <TreeRouteBuilder>(s =>
            {
                var loggerFactory      = s.GetRequiredService <ILoggerFactory>();
                var objectPool         = s.GetRequiredService <ObjectPool <UriBuildingContext> >();
                var constraintResolver = s.GetRequiredService <IInlineConstraintResolver>();
                return(new TreeRouteBuilder(loggerFactory, objectPool, constraintResolver));
            }));

            services.TryAddSingleton(typeof(RoutingMarkerService));

            // Collect all data sources from DI.
            services.TryAddEnumerable(ServiceDescriptor.Transient <IConfigureOptions <EndpointOptions>, ConfigureEndpointOptions>());

            // Allow global access to the list of endpoints.
            services.TryAddSingleton <CompositeEndpointDataSource>(s =>
            {
                var options = s.GetRequiredService <IOptions <EndpointOptions> >();
                return(new CompositeEndpointDataSource(options.Value.DataSources));
            });

            //
            // Endpoint Infrastructure
            //
            services.TryAddSingleton <EndpointDataSource, BuilderEndpointDataSource>();
            services.TryAddSingleton <EndpointDataSourceBuilder, DefaultEndpointDataSourceBuilder>();

            //
            // Default matcher implementation
            //
            services.TryAddSingleton <ParameterPolicyFactory, DefaultParameterPolicyFactory>();
            services.TryAddSingleton <MatcherFactory, DfaMatcherFactory>();
            services.TryAddTransient <DfaMatcherBuilder>();
            services.TryAddSingleton <DfaGraphWriter>();

            // Link generation related services
            services.TryAddSingleton <IEndpointFinder <RouteValuesAddress>, RouteValuesBasedEndpointFinder>();
            services.TryAddSingleton <LinkGenerator, DefaultLinkGenerator>();

            //
            // Endpoint Selection
            //
            services.TryAddSingleton <EndpointSelector, DefaultEndpointSelector>();
            services.TryAddEnumerable(ServiceDescriptor.Singleton <MatcherPolicy, HttpMethodMatcherPolicy>());

            return(services);
        }
Exemple #17
0
 public static AuthenticationBuilder AddTwitter2(this AuthenticationBuilder builder, string authenticationScheme, string displayName, Action <TwitterOptions> configureOptions)
 {
     builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <IPostConfigureOptions <TwitterOptions>, TwitterPostConfigureOptions>());
     return(builder.AddRemoteScheme <TwitterOptions, TwitterHandler2>(authenticationScheme, displayName, configureOptions));
 }
 /// <summary>
 /// Adds <see cref="IStashboxContainer"/> as an <see cref="IServiceProviderFactory{TContainerBuilder}"/>.
 /// </summary>
 /// <param name="services">The service collection.</param>
 /// <param name="container">An already configured <see cref="IStashboxContainer"/> instance to use.</param>
 /// <returns>The service collection.</returns>
 public static IServiceCollection AddStashbox(this IServiceCollection services, IStashboxContainer container) =>
 services.Replace(ServiceDescriptor.Singleton <IServiceProviderFactory <IStashboxContainer> >(new StashboxServiceProviderFactory(container)));
Exemple #19
0
        public static IServiceCollection AddPluginCatalog(this IServiceCollection services, IPluginCatalog pluginCatalog)
        {
            services.TryAddEnumerable(ServiceDescriptor.Singleton(typeof(IPluginCatalog), pluginCatalog));

            return(services);
        }
Exemple #20
0
 private static void AddOpenTelemetryInternal(IServiceCollection services)
 {
     services.TryAddEnumerable(ServiceDescriptor.Singleton <IHostedService, TelemetryHostedService>());
 }
Exemple #21
0
 /// <summary>
 /// Adds a <see cref="ITransformFactory"/> implementation that will be used to read route transform config and generate
 /// the associated transform actions. <see cref="AddTransformFactory{T}(IReverseProxyBuilder)"/> can be called multiple
 /// times to provide multiple distinct types.
 /// </summary>
 public static IReverseProxyBuilder AddTransformFactory <T>(this IReverseProxyBuilder builder) where T : class, ITransformFactory
 {
     builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <ITransformFactory, T>());
     return(builder);
 }
Exemple #22
0
        /// <summary>
        /// Adds Server-Side Blazor services to the service collection.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection"/>.</param>
        /// <param name="configure">A callback to configure <see cref="CircuitOptions"/>.</param>
        /// <returns>An <see cref="IServerSideBlazorBuilder"/> that can be used to further customize the configuration.</returns>
        public static IServerSideBlazorBuilder AddServerSideBlazor(this IServiceCollection services, Action <CircuitOptions> configure = null)
        {
            var builder = new DefaultServerSideBlazorBuilder(services);

            services.AddDataProtection();

            // This call INTENTIONALLY uses the AddHubOptions on the SignalR builder, because it will merge
            // the global HubOptions before running the configure callback. We want to ensure that happens
            // once. Our AddHubOptions method doesn't do this.
            //
            // We need to restrict the set of protocols used by default to our specialized one. Users have
            // the chance to modify options further via the builder.
            //
            // Other than the options, the things exposed by the SignalR builder aren't very meaningful in
            // the Server-Side Blazor context and thus aren't exposed.
            services.AddSignalR().AddHubOptions <ComponentHub>(options =>
            {
                options.SupportedProtocols.Clear();
                options.SupportedProtocols.Add(BlazorPackHubProtocol.ProtocolName);
            });

            // Register the Blazor specific hub protocol
            services.TryAddEnumerable(ServiceDescriptor.Singleton <IHubProtocol, BlazorPackHubProtocol>());

            // Here we add a bunch of services that don't vary in any way based on the
            // user's configuration. So even if the user has multiple independent server-side
            // Components entrypoints, this lot is the same and repeated registrations are a no-op.
            services.TryAddEnumerable(ServiceDescriptor.Singleton <IPostConfigureOptions <StaticFileOptions>, ConfigureStaticFilesOptions>());
            services.TryAddSingleton <CircuitFactory, DefaultCircuitFactory>();

            services.TryAddSingleton <CircuitIdFactory>();

            services.TryAddScoped(s => s.GetRequiredService <ICircuitAccessor>().Circuit);
            services.TryAddScoped <ICircuitAccessor, DefaultCircuitAccessor>();

            services.TryAddSingleton <CircuitRegistry>();

            // We explicitly take over the prerendering and components services here.
            // We can't have two separate component implementations coexisting at the
            // same time, so when you register components (Circuits) it takes over
            // all the abstractions.
            services.AddScoped <IComponentPrerenderer, CircuitPrerenderer>();

            // Standard razor component services implementations
            //
            // These intentionally replace the non-interactive versions included in MVC.
            services.AddScoped <IUriHelper, RemoteUriHelper>();
            services.AddScoped <IJSRuntime, RemoteJSRuntime>();
            services.AddScoped <INavigationInterception, RemoteNavigationInterception>();
            services.AddScoped <IComponentContext, RemoteComponentContext>();
            services.AddScoped <AuthenticationStateProvider, ServerAuthenticationStateProvider>();

            services.TryAddEnumerable(ServiceDescriptor.Singleton <IConfigureOptions <CircuitOptions>, CircuitOptionsJSInteropDetailedErrorsConfiguration>());

            if (configure != null)
            {
                services.Configure(configure);
            }

            return(builder);
        }
 /// <summary>
 /// Adds the <see cref="IHealthCheckService"/> to the container, using the provided delegate to register
 /// health checks.
 /// </summary>
 /// <remarks>
 /// This operation is idempotent - multiple invocations will still only result in a single
 /// <see cref="IHealthCheckService"/> instance in the <see cref="IServiceCollection"/>. It can be invoked
 /// multiple times in order to get access to the <see cref="IHealthChecksBuilder"/> in multiple places.
 /// </remarks>
 /// <param name="services">The <see cref="IServiceCollection"/> to add the <see cref="IHealthCheckService"/> to.</param>
 /// <returns>An instance of <see cref="IHealthChecksBuilder"/> from which health checks can be registered.</returns>
 public static IHealthChecksBuilder AddHealthChecks(this IServiceCollection services)
 {
     services.TryAdd(ServiceDescriptor.Singleton <IHealthCheckService, HealthCheckService>());
     return(new HealthChecksBuilder(services));
 }
Exemple #24
0
 /// <summary> Register <see cref="AspNetCoreHttpScopeProvider" /> in DI as one of the possible implementations for <see cref="IScopeProvider" />. </summary>
 /// <param name="services"> A collection of DI container services. </param>
 /// <returns> Reference to the passed object <paramref name="services" /> to be able to call methods in a chain. </returns>
 public static IServiceCollection AddHttpScope(this IServiceCollection services)
 {
     services.AddHttpContextAccessor();
     services.TryAddEnumerable(ServiceDescriptor.Singleton <IScopeProvider, AspNetCoreHttpScopeProvider>());
     return(services);
 }
        /// <summary>
        ///     Adds Redis distributed lock services to the specified <see cref="IServiceCollection" />.
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection" /> to add services to.</param>
        /// <returns>The <see cref="IServiceCollection" /> so that additional calls can be chained.</returns>
        public static IServiceCollection AddMemoryLock(this IServiceCollection services)
        {
            services.Add(ServiceDescriptor.Singleton <IDistributedLock, MemoryLock>());

            return(services);
        }
Exemple #26
0
        /// <summary>
        /// Registers the OpenIddict token server services in the DI container.
        /// </summary>
        /// <param name="builder">The services builder used by OpenIddict to register new services.</param>
        /// <remarks>This extension can be safely called multiple times.</remarks>
        /// <returns>The <see cref="OpenIddictServerBuilder"/>.</returns>
        public static OpenIddictServerBuilder AddServer([NotNull] this OpenIddictBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            builder.Services.AddAuthentication();
            builder.Services.AddDistributedMemoryCache();
            builder.Services.AddLogging();
            builder.Services.AddMemoryCache();
            builder.Services.AddOptions();

            builder.Services.TryAddScoped <OpenIddictServerEventService>();
            builder.Services.TryAddScoped <OpenIddictServerHandler>();
            builder.Services.TryAddScoped(provider =>
            {
                InvalidOperationException CreateException() => new InvalidOperationException(new StringBuilder()
                                                                                             .AppendLine("The core services must be registered when enabling the OpenIddict server handler.")
                                                                                             .Append("To register the OpenIddict core services, reference the 'OpenIddict.Core' package ")
                                                                                             .Append("and call 'services.AddOpenIddict().AddCore()' from 'ConfigureServices'.")
                                                                                             .ToString());

                return(new OpenIddictServerProvider(
                           provider.GetRequiredService <ILogger <OpenIddictServerProvider> >(),
                           provider.GetRequiredService <OpenIddictServerEventService>(),
                           provider.GetService <IOpenIddictApplicationManager>() ?? throw CreateException(),
                           provider.GetService <IOpenIddictAuthorizationManager>() ?? throw CreateException(),
                           provider.GetService <IOpenIddictScopeManager>() ?? throw CreateException(),
                           provider.GetService <IOpenIddictTokenManager>() ?? throw CreateException()));
            });

            // Register the options initializers used by the OpenID Connect server handler and OpenIddict.
            // Note: TryAddEnumerable() is used here to ensure the initializers are only registered once.
            builder.Services.TryAddEnumerable(new[]
            {
                ServiceDescriptor.Singleton <IPostConfigureOptions <OpenIddictServerOptions>, OpenIddictServerInitializer>(),
                ServiceDescriptor.Singleton <IPostConfigureOptions <OpenIddictServerOptions>, OpenIdConnectServerInitializer>()
            });

            // Register the OpenID Connect server handler in the authentication options,
            // so it can be discovered by the default authentication handler provider.
            builder.Services.Configure <AuthenticationOptions>(options =>
            {
                // Note: this method is guaranteed to be idempotent. To prevent multiple schemes from being
                // registered (which would result in an exception being thrown), a manual check is made here.
                if (options.SchemeMap.TryGetValue(OpenIddictServerDefaults.AuthenticationScheme, out var handler))
                {
                    // If the handler type doesn't correspond to the OpenIddict handler, throw an exception.
                    if (handler.HandlerType != typeof(OpenIddictServerHandler))
                    {
                        throw new InvalidOperationException(new StringBuilder()
                                                            .AppendLine("The OpenIddict server handler cannot be registered as an authentication scheme.")
                                                            .AppendLine("This may indicate that an instance of the OpenID Connect server was registered.")
                                                            .Append("Make sure that 'services.AddAuthentication().AddOpenIdConnectServer()' is not used.")
                                                            .ToString());
                    }

                    return;
                }

                options.AddScheme(OpenIddictServerDefaults.AuthenticationScheme, scheme =>
                {
                    scheme.HandlerType = typeof(OpenIddictServerHandler);
                });
            });

            return(new OpenIddictServerBuilder(builder.Services));
        }
 public static IDataBuilder AddPostgreSQL(this IDataBuilder builder, Action <NpgsqlDbContextOptionsBuilder> npgsqlOptionsAction = null, string dbType = null, IEnumerable <IExtSql> exts = null)
 {
     dbType = dbType ?? "PostgreSQL";
     builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <IDbProvider>(new DbProvider(npgsqlOptionsAction, dbType, exts)));
     return(builder);
 }
Exemple #28
0
 public static IServiceCollection AddReducedHttpClientFactoryLogging(this IServiceCollection services)
 {
     services.Replace(ServiceDescriptor.Singleton <IHttpMessageHandlerBuilderFilter, ReducedLoggingHttpMessageHandlerBuilderFilter>());
     return(services);
 }
Exemple #29
0
 /// <summary>
 /// Enables the MsgPack protocol for SignalR and allows options for the MsgPack protocol to be configured.
 /// </summary>
 /// <remarks>
 /// Any options configured here will be applied, even if the MsgPack protocol has already been registered with the server.
 /// </remarks>
 /// <param name="builder">The <see cref="ISignalRBuilder"/> representing the SignalR server to add MsgPack protocol support to.</param>
 /// <param name="configure">A delegate that can be used to configure the <see cref="MessagePackHubProtocolOptions"/></param>
 /// <returns>The value of <paramref name="builder"/></returns>
 public static TBuilder AddMessagePackProtocol <TBuilder>(this TBuilder builder, Action <MessagePackHubProtocolOptions> configure) where TBuilder : ISignalRBuilder
 {
     builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton <IHubProtocol, MessagePackHubProtocol>());
     builder.Services.Configure(configure);
     return(builder);
 }
Exemple #30
0
 /// <summary>
 /// An <see cref="IXmlEncryptor"/> backed by an X.509 certificate.
 /// </summary>
 public static ServiceDescriptor IXmlEncryptor_Certificate(X509Certificate2 certificate)
 {
     return(ServiceDescriptor.Singleton <IXmlEncryptor>(services => new CertificateXmlEncryptor(certificate, services)));
 }