private static void MultipleImplementationWithReplace() { IServiceCollection services = new ServiceCollection(); services.AddTransient <IHasValue, MyClassWithValue>(); services.Replace(ServiceDescriptor.Transient <IHasValue, MyClassWithValue2>()); var serviceProvider = services.BuildServiceProvider(); var myServices = serviceProvider.GetServices <IHasValue>().ToList(); System.Console.WriteLine("----- Multiple Implemantation Replace ------------"); foreach (var service in myServices) { System.Console.WriteLine(service.Value); } System.Console.WriteLine("--------------------------------------------------"); }
/// <summary> /// Enables Graphites's Plain Text serialization on the metric endpoint's response /// </summary> /// <param name="host">The metrics host builder.</param> /// <returns>The metrics host builder</returns> public static IMetricsHostBuilder AddGraphiteMetricsSerialization(this IMetricsHostBuilder host) { host.Services.Replace(ServiceDescriptor.Transient <IMetricsResponseWriter, GraphiteMetricsResponseWriter>()); return(host); }
// 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 deallocated services.TryAddEnumerable( ServiceDescriptor.Transient <IApplicationModelProvider, DefaultApplicationModelProvider>()); 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>()); // // Resource Filters // services.TryAddTransient <RequestSizeLimitResourceFilter>(); services.TryAddTransient <DisableRequestSizeLimitResourceFilter>(); // // 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 <ObjectResultExecutor>(); services.TryAddSingleton <PhysicalFileResultExecutor>(); services.TryAddSingleton <VirtualFileResultExecutor>(); services.TryAddSingleton <FileStreamResultExecutor>(); services.TryAddSingleton <FileContentResultExecutor>(); services.TryAddSingleton <RedirectResultExecutor>(); services.TryAddSingleton <LocalRedirectResultExecutor>(); services.TryAddSingleton <RedirectToActionResultExecutor>(); services.TryAddSingleton <RedirectToRouteResultExecutor>(); services.TryAddSingleton <RedirectToPageResultExecutor>(); services.TryAddSingleton <ContentResultExecutor>(); // // Route Handlers // services.TryAddSingleton <MvcRouteHandler>(); // Only one per app services.TryAddTransient <MvcAttributeRouteHandler>(); // Many per app // // Middleware pipeline filter related // services.TryAddSingleton <MiddlewareFilterConfigurationProvider>(); // This maintains a cache of middleware pipelines, so it needs to be a singleton services.TryAddSingleton <MiddlewareFilterBuilder>(); }
// Internal for testing. internal static void AddXmlSerializerFormatterServices(IServiceCollection services) { services.TryAddEnumerable( ServiceDescriptor.Transient <IConfigureOptions <MvcOptions>, MvcXmlSerializerMvcOptionsSetup>()); }
/// <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.TryAddTransient <ObjectPoolProvider, DefaultObjectPoolProvider>(); 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)); // Setup global collection of endpoint data sources var dataSources = new ObservableCollection <EndpointDataSource>(); services.TryAddEnumerable(ServiceDescriptor.Transient <IConfigureOptions <RouteOptions>, ConfigureRouteOptions>( serviceProvider => new ConfigureRouteOptions(dataSources))); // Allow global access to the list of endpoints. services.TryAddSingleton <EndpointDataSource>(s => { // Call internal ctor and pass global collection return(new CompositeEndpointDataSource(dataSources)); }); // // Default matcher implementation // services.TryAddSingleton <ParameterPolicyFactory, DefaultParameterPolicyFactory>(); services.TryAddSingleton <MatcherFactory, DfaMatcherFactory>(); services.TryAddTransient <DfaMatcherBuilder>(); services.TryAddSingleton <DfaGraphWriter>(); services.TryAddTransient <DataSourceDependentMatcher.Lifetime>(); services.TryAddSingleton <EndpointMetadataComparer>(services => { // This has no public constructor. return(new EndpointMetadataComparer(services)); }); // Link generation related services services.TryAddSingleton <LinkGenerator, DefaultLinkGenerator>(); services.TryAddSingleton <IEndpointAddressScheme <string>, EndpointNameAddressScheme>(); services.TryAddSingleton <IEndpointAddressScheme <RouteValuesAddress>, RouteValuesAddressScheme>(); services.TryAddSingleton <LinkParser, DefaultLinkParser>(); // // Endpoint Selection // services.TryAddSingleton <EndpointSelector, DefaultEndpointSelector>(); services.TryAddEnumerable(ServiceDescriptor.Singleton <MatcherPolicy, HttpMethodMatcherPolicy>()); services.TryAddEnumerable(ServiceDescriptor.Singleton <MatcherPolicy, HostMatcherPolicy>()); // // Misc infrastructure // services.TryAddSingleton <TemplateBinderFactory, DefaultTemplateBinderFactory>(); services.TryAddSingleton <RoutePatternTransformer, DefaultRoutePatternTransformer>(); return(services); }
/// <summary> /// æ·»åŠ å®žä½“çš„äº‹ä»¶è®¢é˜…å™¨ã€‚ /// </summary> /// <param name="services"></param> /// <returns></returns> public static IServiceCollection AddPersistentSubscriber <TSubscriber>(this IServiceCollection services) where TSubscriber : PersistentSubscriber { services.TryAddEnumerable(ServiceDescriptor.Transient <PersistentSubscriber, TSubscriber>()); return(services); }
// 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 <IActionResultExecutor <ViewResult>, ViewResultExecutor>(); services.TryAddSingleton <IActionResultExecutor <PartialViewResult>, 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 <ModelExpressionProvider>(); // ModelExpressionProvider caches results. Ensure that it's re-used when the requested type is IModelExpressionProvider. services.TryAddSingleton <IModelExpressionProvider>(s => s.GetRequiredService <ModelExpressionProvider>()); services.TryAddSingleton <ValidationHtmlAttributeProvider, DefaultValidationHtmlAttributeProvider>(); services.TryAddSingleton <IJsonHelper, DefaultJsonHelper>(); // // 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 <IActionResultExecutor <ViewComponentResult>, ViewComponentResultExecutor>(); services.TryAddSingleton <ViewComponentInvokerCache>(); services.TryAddTransient <IViewComponentDescriptorProvider, DefaultViewComponentDescriptorProvider>(); services.TryAddSingleton <IViewComponentInvokerFactory, DefaultViewComponentInvokerFactory>(); services.TryAddTransient <IViewComponentHelper, DefaultViewComponentHelper>(); // // Temp Data // services.TryAddEnumerable( ServiceDescriptor.Transient <IApplicationModelProvider, TempDataApplicationModelProvider>()); services.TryAddEnumerable( ServiceDescriptor.Transient <IApplicationModelProvider, ViewDataAttributeApplicationModelProvider>()); services.TryAddSingleton <SaveTempDataFilter>(); // // Component prerendering // services.TryAddSingleton <IComponentPrerenderer, MvcRazorComponentPrerenderer>(); services.TryAddScoped <IUriHelper, HttpUriHelper>(); services.TryAddScoped <IJSRuntime, UnsupportedJavaScriptRuntime>(); services.TryAddTransient <ControllerSaveTempDataPropertyFilter>(); // This does caching so it should stay singleton services.TryAddSingleton <ITempDataProvider, CookieTempDataProvider>(); services.TryAddSingleton <TempDataSerializer, DefaultTempDataSerializer>(); // // Antiforgery // services.TryAddSingleton <ValidateAntiforgeryTokenAuthorizationFilter>(); services.TryAddSingleton <AutoValidateAntiforgeryTokenAuthorizationFilter>(); // These are stateless so their lifetime isn't really important. services.TryAddSingleton <ITempDataDictionaryFactory, TempDataDictionaryFactory>(); services.TryAddSingleton(ArrayPool <ViewBufferValue> .Shared); services.TryAddScoped <IViewBufferScope, MemoryPoolViewBufferScope>(); }
// 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>(); }
// Internal for testing. internal static void AddDataAnnotationsServices(IServiceCollection services) { services.TryAddEnumerable( ServiceDescriptor.Transient <IConfigureOptions <MvcOptions>, MvcDataAnnotationsMvcOptionsSetup>()); services.TryAddSingleton <IValidationAttributeAdapterProvider, ValidationAttributeAdapterProvider>(); }
// Internal for testing. internal static void AddJsonFormatterServices(IServiceCollection services) { services.TryAddEnumerable( ServiceDescriptor.Transient <IConfigureOptions <MvcOptions>, MvcJsonMvcOptionsSetup>()); services.TryAddSingleton <JsonResultExecutor>(); }
/// <summary> /// Enables InfluxDB's Line Protocol serialization on the metric endpoint's response /// </summary> /// <param name="host">The metrics host builder.</param> /// <returns>The metrics host builder</returns> public static IMetricsHostBuilder AddInfluxDBLineProtocolMetricsTextSerialization(this IMetricsHostBuilder host) { host.Services.Replace(ServiceDescriptor.Transient <IMetricsTextResponseWriter, LineProtocolTextResponseWriter>()); return(host); }
public static IServiceCollection AddAutoMapperObjectMapper(this IServiceCollection services) { return(services.Replace( ServiceDescriptor.Transient <IAutoObjectMappingProvider, AutoMapperAutoObjectMappingProvider> () )); }
/// <summary> /// Adds an implementation of <see cref="ISaml2pPartnerStore"/>. /// <para>This service is registered in <see cref="ServiceLifetime.Transient"/> scope.</para> /// </summary> /// <typeparam name="TStore">The type to register.</typeparam> /// <param name="services">The <see cref="IServiceCollection"/> instance to add service to.</param> /// <returns>The <see cref="IServiceCollection"/> instance so that additional calls can be chained.</returns> public static IServiceCollection AddSaml2pPartnerStore <TStore>(this IServiceCollection services) where TStore : class, ISaml2pPartnerStore { services.TryAddEnumerable(ServiceDescriptor.Transient <ISaml2pPartnerStore, TStore>()); return(services); }
/// <summary> /// Adds an implementation of <see cref="IServiceProviderClaimsProvider"/>. /// <para>This service is registered in <see cref="ServiceLifetime.Transient"/> scope.</para> /// </summary> /// <typeparam name="TClaimStore">The type to register.</typeparam> /// <param name="services">The <see cref="IServiceCollection"/> instance to add service to.</param> /// <returns>The <see cref="IServiceCollection"/> instance so that additional calls can be chained.</returns> public static IServiceCollection AddSaml2pServiceProviderClaimStore <TClaimStore>(this IServiceCollection services) where TClaimStore : class, IServiceProviderClaimsProvider { services.TryAddEnumerable(ServiceDescriptor.Transient <IServiceProviderClaimsProvider, TClaimStore>()); return(services); }
/// <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); }
// Internal for testing. internal static void AddApiExplorerServices(IServiceCollection services) { services.TryAddSingleton <IApiDescriptionGroupCollectionProvider, ApiDescriptionGroupCollectionProvider>(); services.TryAddEnumerable( ServiceDescriptor.Transient <IApiDescriptionProvider, DefaultApiDescriptionProvider>()); }
public static CrawlerBuilder UseHttpClient(this CrawlerBuilder builder, Func <HttpRequestMessage, Task <HttpResponseMessage> > send) { builder.Services.Replace(ServiceDescriptor.Transient <IHttpClient>(p => new DefaultHttpClient(send))); return(builder); }
/// <summary> /// /// </summary> /// <param name="services"></param> /// <param name="logAction">logAction</param> /// <para>e.g. .Logs or wwwroor/logs or C:/wwwroot/logs</para> public static IServiceCollection AddFileLog(this IServiceCollection services, Action <LogOptions> logAction = null) { if (!services.Any(x => x.ImplementationType == typeof(LOG.LoggerFactory))) { LogOptions logOptions = new LogOptions(); logAction?.Invoke(logOptions); services.Replace(ServiceDescriptor.Transient <IApplicationBuilderFactory, DefaultApplicationBuilderFactory>()); //LoggerSettings.Format = logOptions.Format; LOG.LoggerFactory.ServiceCollection = services; if (string.IsNullOrEmpty(logOptions.LogDirectory)) { logOptions.LogDirectory = ".Logs"; } services.AddHttpContextAccessor(); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Console.OutputEncoding = System.Text.Encoding.UTF8; var _config = services.FirstOrDefault(x => x.ServiceType == typeof(IConfiguration))?.ImplementationInstance as IConfiguration; if (_config == null) { _config = new ConfigurationBuilder() .AddEnvironmentVariables("ASPNETCORE_") .SetBasePath(AppContext.BaseDirectory) .Build(); _config[WebHostDefaults.ContentRootKey] = AppContext.BaseDirectory; services.AddSingleton(_config); } if (string.IsNullOrEmpty(_config[WebHostDefaults.ContentRootKey])) { _config[WebHostDefaults.ContentRootKey] = AppContext.BaseDirectory; } IHostingEnvironment environment = (IHostingEnvironment)services.FirstOrDefault(x => x.ServiceType == typeof(IHostingEnvironment)) ?.ImplementationInstance; if (environment == null) { WebHostOptions options = new WebHostOptions(_config, Assembly.GetEntryAssembly().GetName().Name); environment = new HostingEnvironment(); environment.Initialize(AppContext.BaseDirectory, options); services.TryAddSingleton <IHostingEnvironment>(environment); } if (string.IsNullOrEmpty(environment.WebRootPath)) { var _contentPath = _config[WebHostDefaults.ContentRootKey]; var binIndex = _contentPath.LastIndexOf("\\bin\\"); if (binIndex > -1) { var contentPath = _contentPath.Substring(0, binIndex); if (contentPath.IndexOf(environment.ApplicationName) > -1) { _config[WebHostDefaults.ContentRootKey] = contentPath; environment.ContentRootPath = contentPath; environment.WebRootPath = System.IO.Path.Combine(contentPath, "wwwroot"); } else { environment.WebRootPath = _contentPath; } } else { environment.WebRootPath = System.IO.Path.Combine(_config["ContentRoot"], "wwwroot"); } } if (Path.IsPathRooted(logOptions.LogDirectory)) { LoggerSettings.LogDirectory = logOptions.LogDirectory; } else { LoggerSettings.LogDirectory = Path.Combine(_config["ContentRoot"], logOptions.LogDirectory); } if (!Directory.Exists(LoggerSettings.LogDirectory)) { Directory.CreateDirectory(LoggerSettings.LogDirectory); } var path = Path.Combine(LoggerSettings.LogDirectory, LoggerSettings.LogJsonFileName); if (!File.Exists(path)) { File.AppendAllText(path, LoggerSettings.LoggingJsonContent); } if (logOptions.LogAdapters.Count == 0) { logOptions.UseText(); } ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder .SetBasePath(environment.ContentRootPath) .AddJsonFile(path, true, true); var configuration = configurationBuilder.Build(); services.RemoveAll <ILoggerProviderConfigurationFactory>(); services.RemoveAll(typeof(ILoggerProviderConfiguration <>)); var type = typeof(ILoggerProviderConfigurationFactory).Assembly.DefinedTypes .SingleOrDefault(t => t.Name == "LoggingConfiguration"); services.RemoveAll(type); services.AddLogging(x => { x.AddConfiguration(configuration); if (!x.Services.Any(t => t.ServiceType == typeof(ILoggerProvider))) { x.AddConsole(); } x.Services.RemoveAll <IConfigureOptions <Logging.LoggerFilterOptions> >(); x.Services.AddSingleton <IConfigureOptions <Logging.LoggerFilterOptions> >(new LOG.LoggerFilterConfigureOptions(configuration)); }); services.TryAddEnumerable(logOptions.LogAdapters); logOptions.LogAdapters.Clear(); services.Replace(ServiceDescriptor.Singleton <ILoggerFactory, LOG.LoggerFactory>()); services.Replace(ServiceDescriptor.Singleton <DiagnosticSource>(new DefaultDiagnosticListener())); if (services.IsHttpRequest()) { MarkdownFileMiddleware.SaveResourceFiles(environment.WebRootPath); } DefaultApplicationBuilderFactory.OnCreateBuilder(UseFileLog, logOptions); } return(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>, MvcCoreMvcOptionsSetup>()); 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.TryAddSingleton <ApplicationModelFactory>(); services.TryAddEnumerable( ServiceDescriptor.Transient <IApplicationModelProvider, DefaultApplicationModelProvider>()); services.TryAddEnumerable( ServiceDescriptor.Transient <IApplicationModelProvider, ApiBehaviorApplicationModelProvider>()); services.TryAddEnumerable( ServiceDescriptor.Transient <IActionDescriptorProvider, ControllerActionDescriptorProvider>()); services.TryAddSingleton <IActionDescriptorCollectionProvider, DefaultActionDescriptorCollectionProvider>(); // // Action Selection // services.TryAddSingleton <IActionSelector, ActionSelector>(); services.TryAddSingleton <ActionConstraintCache>(); // Will be cached by the DefaultActionSelector services.TryAddEnumerable(ServiceDescriptor.Transient <IActionConstraintProvider, DefaultActionConstraintProvider>()); // Policies for Endpoints services.TryAddEnumerable(ServiceDescriptor.Singleton <MatcherPolicy, ActionConstraintMatcherPolicy>()); // // 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, options)); }); 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>(); services.TryAddSingleton <IActionResultExecutor <JsonResult>, SystemTextJsonResultExecutor>(); services.TryAddSingleton <IClientErrorFactory, ProblemDetailsClientErrorFactory>(); services.TryAddSingleton <ProblemDetailsFactory, DefaultProblemDetailsFactory>(); // // Route Handlers // services.TryAddSingleton <MvcRouteHandler>(); // Only one per app services.TryAddTransient <MvcAttributeRouteHandler>(); // Many per app // // Endpoint Routing / Endpoints // services.TryAddSingleton <ControllerActionEndpointDataSourceFactory>(); services.TryAddSingleton <OrderedEndpointsSequenceProviderCache>(); services.TryAddSingleton <ControllerActionEndpointDataSourceIdProvider>(); services.TryAddSingleton <ActionEndpointFactory>(); services.TryAddSingleton <DynamicControllerEndpointSelectorCache>(); services.TryAddEnumerable(ServiceDescriptor.Singleton <MatcherPolicy, DynamicControllerEndpointMatcherPolicy>()); services.TryAddEnumerable(ServiceDescriptor.Singleton <IRequestDelegateFactory, ControllerRequestDelegateFactory>()); // // 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>()); }
/// <summary> /// Enables Plain Text serialization on the metric endpoint's response /// </summary> /// <param name="host">The metrics host builder.</param> /// <returns>The metrics host builder</returns> public static IMetricsHostBuilder AddAsciiMetricsTextSerialization(this IMetricsHostBuilder host) { host.Services.Replace(ServiceDescriptor.Transient <IMetricsTextResponseWriter, AsciiMetricsTextResponseWriter>()); return(host); }
/// <summary> /// Adds tenant level services for managing liquid view template files. /// </summary> public static OrchardCoreBuilder AddLiquidViews(this OrchardCoreBuilder builder) { builder.ConfigureServices(services => { services.AddSingleton <LiquidViewParser>(); services.AddSingleton <IAnchorTag, AnchorTag>(); services.AddTransient <IConfigureOptions <TemplateOptions>, TemplateOptionsFileProviderSetup>(); services.TryAddEnumerable( ServiceDescriptor.Transient <IConfigureOptions <LiquidViewOptions>, LiquidViewOptionsSetup>()); services.TryAddEnumerable( ServiceDescriptor.Transient <IConfigureOptions <ShapeTemplateOptions>, LiquidShapeTemplateOptionsSetup>()); services.AddSingleton <IApplicationFeatureProvider <ViewsFeature>, LiquidViewsFeatureProvider>(); services.AddScoped <IRazorViewExtensionProvider, LiquidViewExtensionProvider>(); services.AddSingleton <LiquidTagHelperFactory>(); services.Configure <TemplateOptions>(o => { o.ValueConverters.Add(x => { if (x is Shape s) { return(new ObjectValue(s)); } if (!(o is IShape) && o is IHtmlContent c) { return(new HtmlContentValue(c)); } return(null); }); o.MemberAccessStrategy.Register <Shape>("*", new ShapeAccessor()); o.MemberAccessStrategy.Register <ZoneHolding>("*", new ShapeAccessor()); o.MemberAccessStrategy.Register <ShapeMetadata>(); o.Scope.SetValue("Culture", new ObjectValue(new LiquidCultureAccessor())); o.MemberAccessStrategy.Register <LiquidCultureAccessor, FluidValue>((obj, name, ctx) => { return(name switch { nameof(CultureInfo.Name) => new StringValue(CultureInfo.CurrentUICulture.Name), "Dir" => new StringValue(CultureInfo.CurrentUICulture.GetLanguageDirection()), _ => NilValue.Instance }); }); o.Scope.SetValue("Request", new ObjectValue(new LiquidRequestAccessor())); o.MemberAccessStrategy.Register <LiquidRequestAccessor, FluidValue>((obj, name, ctx) => { var request = ((LiquidTemplateContext)ctx).Services.GetRequiredService <IHttpContextAccessor>().HttpContext?.Request; if (request != null) { return(name switch { nameof(HttpRequest.QueryString) => new StringValue(request.QueryString.Value), nameof(HttpRequest.ContentType) => new StringValue(request.ContentType), nameof(HttpRequest.ContentLength) => NumberValue.Create(request.ContentLength ?? 0), nameof(HttpRequest.Cookies) => new ObjectValue(new CookieCollectionWrapper(request.Cookies)), nameof(HttpRequest.Headers) => new ObjectValue(new HeaderDictionaryWrapper(request.Headers)), nameof(HttpRequest.Query) => new ObjectValue(new QueryCollection(request.Query.ToDictionary(kv => kv.Key, kv => kv.Value))), nameof(HttpRequest.Form) => request.HasFormContentType ? (FluidValue) new ObjectValue(request.Form) : NilValue.Instance, nameof(HttpRequest.Protocol) => new StringValue(request.Protocol), nameof(HttpRequest.Path) => new StringValue(request.Path.Value), nameof(HttpRequest.PathBase) => new StringValue(request.PathBase.Value), nameof(HttpRequest.Host) => new StringValue(request.Host.Value), nameof(HttpRequest.IsHttps) => BooleanValue.Create(request.IsHttps), nameof(HttpRequest.Scheme) => new StringValue(request.Scheme), nameof(HttpRequest.Method) => new StringValue(request.Method), nameof(HttpRequest.RouteValues) => new ObjectValue(new RouteValueDictionaryWrapper(request.RouteValues)), // Provides correct escaping to reconstruct a request or redirect URI. "UriHost" => new StringValue(request.Host.ToUriComponent(), encode: false), "UriPath" => new StringValue(request.Path.ToUriComponent(), encode: false), "UriPathBase" => new StringValue(request.PathBase.ToUriComponent(), encode: false), "UriQueryString" => new StringValue(request.QueryString.ToUriComponent(), encode: false), _ => NilValue.Instance }); } return(NilValue.Instance); });
public static void AddMyIdentity(this IServiceCollection services, IConfiguration config) { IdentityModelEventSource.ShowPII = true; var identityOptions = config.GetSection("identity").Get <NotifoIdentityOptions>() ?? new NotifoIdentityOptions(); services.Configure <NotifoIdentityOptions>( config.GetSection("identity")); services.AddIdentity <NotifoUser, NotifoRole>() .AddDefaultTokenProviders(); services.AddSingletonAs <UserResolver>() .As <IUserResolver>(); services.AddSingletonAs <MongoDbUserStore>() .As <IUserStore <NotifoUser> >().As <IUserFactory>(); services.AddSingletonAs <MongoDbRoleStore>() .As <IRoleStore <NotifoRole> >(); services.AddSingletonAs <MongoDbPersistedGrantStore>() .As <IPersistedGrantStore>(); services.AddSingletonAs <MongoDbKeyStore>() .As <ISigningCredentialStore>().As <IValidationKeysStore>(); services.AddSingletonAs <UserCreator>() .AsSelf(); services.AddIdentityServer() .AddAspNetIdentity <NotifoUser>() .AddClients() .AddIdentityResources() .AddApiResources(); services.Configure <ApiAuthorizationOptions>(options => { options.Clients.AddIdentityServerSPA("notifo", client => client .WithLogoutRedirectUri("/authentication/logout-callback") .WithRedirectUri("/authentication/login-callback") .WithRedirectUri("/authentication/login-silent-callback.html")); }); services.AddAuthorization(); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = AlternativeSchema; options.DefaultChallengeScheme = AlternativeSchema; }) .AddPolicyScheme(AlternativeSchema, null, options => { options.ForwardDefaultSelector = context => { if (ApiKeyHandler.IsApiKey(context.Request, out _)) { return(ApiKeyDefaults.AuthenticationScheme); } return("IdentityServerJwt"); }; }) .AddGoogle(identityOptions) .AddGithub(identityOptions) .AddApiKey() .AddIdentityServerJwt(); services.TryAddEnumerable(ServiceDescriptor.Transient <IConfigureOptions <IdentityServerOptions>, IdentityOptions>()); services.AddMyCertStore(); }
// Internal for testing. internal static void AddServices(IServiceCollection services) { services.TryAddEnumerable( ServiceDescriptor.Transient <IConfigureOptions <MvcRazorRuntimeCompilationOptions>, MvcRazorRuntimeCompilationOptionsSetup>()); var compilerProvider = services.FirstOrDefault(f => f.ServiceType == typeof(IViewCompilerProvider) && f.ImplementationType?.Assembly == typeof(IViewCompilerProvider).Assembly && f.ImplementationType.FullName == "Microsoft.AspNetCore.Mvc.Razor.Compilation.DefaultViewCompilerProvider"); if (compilerProvider != null) { // Replace the default implementation of IViewCompilerProvider services.Remove(compilerProvider); } services.TryAddSingleton <IViewCompilerProvider, RuntimeViewCompilerProvider>(); var actionDescriptorProvider = services.FirstOrDefault(f => f.ServiceType == typeof(IActionDescriptorProvider) && f.ImplementationType == typeof(CompiledPageActionDescriptorProvider)); if (actionDescriptorProvider != null) { services.Remove(actionDescriptorProvider); // Add PageActionDescriptorProvider and the matcher policy that supports runtime compilation. // We only want to add support for this if we know AddRazorPages was called. In the absence of this, several services registered by Razor Pages // will be absent. We'll use the presence of the CompiledPageActionDescriptorProvider service as a poor way to test this. services.TryAddEnumerable( ServiceDescriptor.Singleton <IActionDescriptorProvider, PageActionDescriptorProvider>()); services.TryAddEnumerable(ServiceDescriptor.Singleton <MatcherPolicy, PageLoaderMatcherPolicy>()); } services.TryAddSingleton <RuntimeCompilationFileProvider>(); services.TryAddSingleton <RazorReferenceManager>(); services.TryAddSingleton <CSharpCompiler>(); services.TryAddSingleton <RazorProjectFileSystem, FileProviderRazorProjectFileSystem>(); services.TryAddSingleton(s => { var fileSystem = s.GetRequiredService <RazorProjectFileSystem>(); var csharpCompiler = s.GetRequiredService <CSharpCompiler>(); var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder => { RazorExtensions.Register(builder); // Roslyn + TagHelpers infrastructure var referenceManager = s.GetRequiredService <RazorReferenceManager>(); builder.Features.Add(new LazyMetadataReferenceFeature(referenceManager)); builder.Features.Add(new CompilationTagHelperFeature()); // TagHelperDescriptorProviders (actually do tag helper discovery) builder.Features.Add(new DefaultTagHelperDescriptorProvider()); builder.Features.Add(new ViewComponentTagHelperDescriptorProvider()); builder.SetCSharpLanguageVersion(csharpCompiler.ParseOptions.LanguageVersion); }); return(projectEngine); }); // // Razor Pages // services.TryAddEnumerable( ServiceDescriptor.Singleton <IPageRouteModelProvider, RazorProjectPageRouteModelProvider>()); services.TryAddEnumerable( ServiceDescriptor.Singleton <IActionDescriptorChangeProvider, PageActionDescriptorChangeProvider>()); }
// Internal for testing. internal static void AddRazorViewEngineServices(IServiceCollection services) { services.TryAddSingleton <CSharpCompiler>(); #pragma warning disable CS0618 // Type or member is obsolete services.TryAddSingleton <RazorReferenceManager, DefaultRazorReferenceManager>(); #pragma warning restore CS0618 // Type or member is obsolete services.TryAddEnumerable( ServiceDescriptor.Transient <IConfigureOptions <MvcViewOptions>, MvcRazorMvcViewOptionsSetup>()); services.TryAddEnumerable( ServiceDescriptor.Transient <IConfigureOptions <RazorViewEngineOptions>, RazorViewEngineOptionsSetup>()); services.TryAddEnumerable( ServiceDescriptor.Transient <IPostConfigureOptions <RazorViewEngineOptions>, RazorViewEngineOptionsSetup>()); services.TryAddSingleton < IRazorViewEngineFileProviderAccessor, DefaultRazorViewEngineFileProviderAccessor>(); services.TryAddSingleton <IRazorViewEngine>(s => { var pageFactory = s.GetRequiredService <IRazorPageFactoryProvider>(); var pageActivator = s.GetRequiredService <IRazorPageActivator>(); var htmlEncoder = s.GetRequiredService <HtmlEncoder>(); var optionsAccessor = s.GetRequiredService <IOptions <RazorViewEngineOptions> >(); var razorFileSystem = s.GetRequiredService <RazorProjectFileSystem>(); var loggerFactory = s.GetRequiredService <ILoggerFactory>(); var diagnosticSource = s.GetRequiredService <DiagnosticSource>(); var viewEngine = new RazorViewEngine(pageFactory, pageActivator, htmlEncoder, optionsAccessor, razorFileSystem, loggerFactory, diagnosticSource); return(viewEngine); }); services.TryAddSingleton <IViewCompilerProvider, RazorViewCompilerProvider>(); services.TryAddSingleton <IViewCompilationMemoryCacheProvider, RazorViewCompilationMemoryCacheProvider>(); // In the default scenario the following services are singleton by virtue of being initialized as part of // creating the singleton RazorViewEngine instance. services.TryAddTransient <IRazorPageFactoryProvider, DefaultRazorPageFactoryProvider>(); // // Razor compilation infrastructure // services.TryAddSingleton <LazyMetadataReferenceFeature>(); services.TryAddSingleton <RazorProjectFileSystem, FileProviderRazorProjectFileSystem>(); services.TryAddSingleton(s => { var fileSystem = s.GetRequiredService <RazorProjectFileSystem>(); var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder => { RazorExtensions.Register(builder); // Roslyn + TagHelpers infrastructure var metadataReferenceFeature = s.GetRequiredService <LazyMetadataReferenceFeature>(); builder.Features.Add(metadataReferenceFeature); builder.Features.Add(new CompilationTagHelperFeature()); // TagHelperDescriptorProviders (actually do tag helper discovery) builder.Features.Add(new DefaultTagHelperDescriptorProvider()); builder.Features.Add(new ViewComponentTagHelperDescriptorProvider()); }); return(projectEngine); }); // Legacy Razor compilation services services.TryAddSingleton <RazorProject>(s => s.GetRequiredService <RazorProjectEngine>().FileSystem); services.TryAddSingleton <RazorTemplateEngine, MvcRazorTemplateEngine>(); services.TryAddSingleton(s => s.GetRequiredService <RazorProjectEngine>().Engine); // This caches Razor page activation details that are valid for the lifetime of the application. services.TryAddSingleton <IRazorPageActivator, RazorPageActivator>(); // Only want one ITagHelperActivator and ITagHelperComponentPropertyActivator so it can cache Type activation information. Types won't conflict. services.TryAddSingleton <ITagHelperActivator, DefaultTagHelperActivator>(); services.TryAddSingleton <ITagHelperComponentPropertyActivator, TagHelperComponentPropertyActivator>(); services.TryAddSingleton <ITagHelperFactory, DefaultTagHelperFactory>(); // TagHelperComponents manager services.TryAddScoped <ITagHelperComponentManager, TagHelperComponentManager>(); // Consumed by the Cache tag helper to cache results across the lifetime of the application. services.TryAddSingleton <IMemoryCache, MemoryCache>(); services.TryAddSingleton <TagHelperMemoryCacheProvider>(); }
/// <summary> /// Adds host and tenant level services for managing themes. /// </summary> public static OrchardCoreBuilder AddTheming(this OrchardCoreBuilder builder) { builder.AddThemingHost() .ConfigureServices(services => { services.Configure <MvcOptions>((options) => { options.Filters.Add(typeof(ModelBinderAccessorFilter)); options.Filters.Add(typeof(NotifyFilter)); options.Filters.Add(typeof(RazorViewActionFilter)); }); // Used as a service when we create a fake 'ActionContext'. services.AddScoped <IAsyncViewActionFilter, RazorViewActionFilter>(); services.AddScoped <IUpdateModelAccessor, LocalModelBinderAccessor>(); services.AddScoped <ViewContextAccessor>(); services.AddScoped <IShapeTemplateViewEngine, RazorShapeTemplateViewEngine>(); services.AddSingleton <IApplicationFeatureProvider <ViewsFeature>, ThemingViewsFeatureProvider>(); services.AddScoped <IViewLocationExpanderProvider, ThemeViewLocationExpanderProvider>(); services.AddScoped <IShapeTemplateHarvester, BasicShapeTemplateHarvester>(); services.AddTransient <IShapeTableManager, DefaultShapeTableManager>(); services.AddScoped <IShapeTableProvider, ShapeAttributeBindingStrategy>(); services.AddScoped <IShapeTableProvider, ShapePlacementParsingStrategy>(); services.AddScoped <IShapeTableProvider, ShapeTemplateBindingStrategy>(); services.AddScoped <IPlacementNodeFilterProvider, PathPlacementNodeFilterProvider>(); services.TryAddEnumerable( ServiceDescriptor.Transient <IConfigureOptions <ShapeTemplateOptions>, ShapeTemplateOptionsSetup>()); services.TryAddSingleton <IShapeTemplateFileProviderAccessor, ShapeTemplateFileProviderAccessor>(); services.AddShapeAttributes <CoreShapes>(); services.AddScoped <IShapeTableProvider, CoreShapesTableProvider>(); services.AddShapeAttributes <ZoneShapes>(); services.AddScoped <IHtmlDisplay, DefaultHtmlDisplay>(); services.AddScoped <ILayoutAccessor, LayoutAccessor>(); services.AddScoped <IThemeManager, ThemeManager>(); services.AddScoped <IPageTitleBuilder, PageTitleBuilder>(); services.AddScoped <IShapeFactory, DefaultShapeFactory>(); services.AddScoped <IDisplayHelper, DisplayHelper>(); services.AddScoped <INotifier, Notifier>(); services.AddShapeAttributes <DateTimeShapes>(); services.AddShapeAttributes <PageTitleShapes>(); services.AddTagHelpers <AddAlternateTagHelper>(); services.AddTagHelpers <AddClassTagHelper>(); services.AddTagHelpers <AddWrapperTagHelper>(); services.AddTagHelpers <BaseShapeTagHelper>(); services.AddTagHelpers <ClearAlternatesTagHelper>(); services.AddTagHelpers <ClearClassesTagHelper>(); services.AddTagHelpers <ClearWrappersTagHelper>(); services.AddTagHelpers <InputIsDisabledTagHelper>(); services.AddTagHelpers <RemoveAlternateTagHelper>(); services.AddTagHelpers <RemoveClassTagHelper>(); services.AddTagHelpers <RemoveWrapperTagHelper>(); services.AddTagHelpers <ShapeMetadataTagHelper>(); services.AddTagHelpers <ShapeTagHelper>(); services.AddTagHelpers <ValidationMessageTagHelper>(); services.AddTagHelpers <ZoneTagHelper>(); }); return(builder); }
/// <summary> /// Registers HTTP-specific functionality and handling to this API instance. /// </summary> /// <param name="apiBuilder">The builder to register with.</param> /// <param name="configure">An optional action that can configure <see cref="BlueprintHttpBuilder" />, executed /// <c>after</c> the default configuration has been run.</param> /// <returns>This builder.</returns> public static BlueprintApiBuilder Http( this BlueprintApiBuilder apiBuilder, Action <BlueprintHttpBuilder> configure = null) { apiBuilder.Services.AddSingleton <IHttpRequestStreamReaderFactory, MemoryPoolHttpRequestStreamReaderFactory>(); apiBuilder.Services.AddSingleton <IHttpResponseStreamWriterFactory, MemoryPoolHttpResponseStreamWriterFactory>(); apiBuilder.Services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>(); apiBuilder.Services.AddOptions <BlueprintHttpOptions>(); apiBuilder.Services.AddOptions <BlueprintJsonOptions>(); apiBuilder.Services.Add(ServiceDescriptor.Transient <IConfigureOptions <BlueprintHttpOptions>, BlueprintHttpOptionsSetup>()); apiBuilder.Services.AddSingleton <IOutputFormatterSelector, DefaultOutputFormatterSelector>(); apiBuilder.Services.AddScoped <IApiLinkGenerator, ApiLinkGenerator>(); apiBuilder.AddMessageSource <HttpRouteMessagePopulationSource>(); apiBuilder.AddMessageSource <HttpBodyMessagePopulationSource>(); // "Owned" HTTP part sources apiBuilder.AddMessageSource( HttpPartMessagePopulationSource.Owned <FromCookieAttribute>( c => c.GetProperty("Request").GetProperty(nameof(HttpRequest.Cookies)), false)); apiBuilder.AddMessageSource( HttpPartMessagePopulationSource.Owned <FromHeaderAttribute>( c => c.GetProperty("Request").GetProperty(nameof(HttpRequest.Headers)), true)); apiBuilder.AddMessageSource( HttpPartMessagePopulationSource.Owned <FromQueryAttribute>( c => c.GetProperty("Request").GetProperty(nameof(HttpRequest.Query)), true)); // Catch-all query string population source apiBuilder.AddMessageSource( HttpPartMessagePopulationSource.CatchAll( "fromQuery", c => c.GetProperty("Request").GetProperty(nameof(HttpRequest.Query)), c => c.Descriptor.GetFeatureData <HttpOperationFeatureData>().HttpMethod == "GET", true)); apiBuilder.Services.AddSingleton <IOperationResultExecutor <ValidationFailedOperationResult>, ValidationFailedOperationResultExecutor>(); apiBuilder.Services.AddSingleton <IOperationResultExecutor <UnhandledExceptionOperationResult>, UnhandledExceptionOperationResultExecutor>(); apiBuilder.Services.AddSingleton <IOperationResultExecutor <OkResult>, OkResultOperationExecutor>(); apiBuilder.Services.AddSingleton <OkResultOperationExecutor>(); apiBuilder.Services.AddSingleton <IContextMetadataProvider, HttpContextMetadataProvider>(); apiBuilder.Operations(o => o .AddOperation <RootMetadataOperation>("AddHttp") .AddConvention(new HttpOperationScannerConvention())); apiBuilder.Compilation(c => c.AddVariableSource(new HttpVariableSource())); configure?.Invoke(new BlueprintHttpBuilder(apiBuilder.Services)); return(apiBuilder); }
// To enable unit testing internal static void AddMvcCoreServices(IServiceCollection services) { // // RuntimeServices // if (PlatformServices.Default?.LibraryManager != null) { services.TryAddSingleton(PlatformServices.Default.LibraryManager); } // // 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 <IActionDescriptorCollectionProvider, DefaultActionDescriptorCollectionProvider>(); // // 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 // // The IActionInvokerFactory is cachable services.TryAddSingleton <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> >().Value; return(new DefaultCompositeMetadataDetailsProvider(options.ModelMetadataDetailsProviders)); })); services.TryAddSingleton <IObjectModelValidator, DefaultObjectValidator>(); // // Random Infrastructure // services.TryAddSingleton <MvcMarkerService, MvcMarkerService>(); services.TryAddSingleton <ITypeActivatorCache, DefaultTypeActivatorCache>(); services.TryAddSingleton <IUrlHelperFactory, UrlHelperFactory>(); services.TryAddSingleton <IHttpRequestStreamReaderFactory, MemoryPoolHttpRequestStreamReaderFactory>(); services.TryAddSingleton <IHttpResponseStreamWriterFactory, MemoryPoolHttpResponseStreamWriterFactory>(); services.TryAddSingleton(ArrayPool <byte> .Shared); services.TryAddSingleton(ArrayPool <char> .Shared); services.TryAddSingleton <ObjectResultExecutor>(); }
/// <summary> /// /// </summary> /// <param name="services"></param> /// <param name="logAction">logAction</param> /// <para>e.g. .Logs or wwwroor/logs or C:/wwwroot/logs</para> public static IServiceCollection AddFileLog(this IServiceCollection services, Action <LogOptions> logAction = null) { bool flag = !services.Any((ServiceDescriptor x) => x.ImplementationType == typeof(LoggerFactory)); if (flag) { LogOptions logOptions = new LogOptions(); if (logAction != null) { logAction(logOptions); } services.Replace(ServiceDescriptor.Transient <IApplicationBuilderFactory, DefaultApplicationBuilderFactory>()); LoggerSettings.Format = logOptions.Format; LoggerFactory.ServiceCollection = services; bool flag2 = string.IsNullOrEmpty(logOptions.LogDirectory); if (flag2) { logOptions.LogDirectory = ".Logs"; } services.AddHttpContextAccessor(); services.AddSingleton <ILogAdapter, FileLogAdapter>(); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Console.OutputEncoding = Encoding.UTF8; ServiceDescriptor serviceDescriptor = services.FirstOrDefault((ServiceDescriptor x) => x.ServiceType == typeof(IConfiguration)); IConfiguration _config = ((serviceDescriptor != null) ? serviceDescriptor.ImplementationInstance : null) as IConfiguration; bool flag3 = _config == null; if (flag3) { _config = FileConfigurationExtensions.SetBasePath(EnvironmentVariablesExtensions.AddEnvironmentVariables(new ConfigurationBuilder(), "ASPNETCORE_"), AppContext.BaseDirectory).Build(); _config[WebHostDefaults.ContentRootKey] = AppContext.BaseDirectory; services.AddSingleton(_config); } bool flag4 = string.IsNullOrEmpty(_config[WebHostDefaults.ContentRootKey]); if (flag4) { _config[WebHostDefaults.ContentRootKey] = AppContext.BaseDirectory; } ServiceDescriptor serviceDescriptor2 = services.FirstOrDefault((ServiceDescriptor x) => x.ServiceType == typeof(IHostingEnvironment)); IHostingEnvironment environment = (IHostingEnvironment)((serviceDescriptor2 != null) ? serviceDescriptor2.ImplementationInstance : null); bool flag5 = environment == null; if (flag5) { WebHostOptions options = new WebHostOptions(_config, Assembly.GetEntryAssembly().GetName().Name); environment = new HostingEnvironment(); HostingEnvironmentExtensions.Initialize(environment, AppContext.BaseDirectory, options); services.TryAddSingleton(environment); } bool flag6 = string.IsNullOrEmpty(environment.WebRootPath); if (flag6) { string _contentPath = _config[WebHostDefaults.ContentRootKey]; int binIndex = _contentPath.LastIndexOf("\\bin\\"); bool flag7 = binIndex > -1; if (flag7) { string contentPath = _contentPath.Substring(0, binIndex); bool flag8 = contentPath.IndexOf(environment.ApplicationName) > -1; if (flag8) { _config[WebHostDefaults.ContentRootKey] = contentPath; environment.ContentRootPath = contentPath; environment.WebRootPath = Path.Combine(contentPath, "wwwroot"); } else { environment.WebRootPath = _contentPath; } } else { environment.WebRootPath = Path.Combine(_config["ContentRoot"], "wwwroot"); } } bool flag9 = Path.IsPathRooted(logOptions.LogDirectory); if (flag9) { LoggerSettings.LogDirectory = logOptions.LogDirectory; } else { LoggerSettings.LogDirectory = Path.Combine(_config["ContentRoot"], logOptions.LogDirectory); } bool flag10 = !Directory.Exists(LoggerSettings.LogDirectory); if (flag10) { Directory.CreateDirectory(LoggerSettings.LogDirectory); } string path = Path.Combine(LoggerSettings.LogDirectory, "_logging.json"); bool flag11 = !File.Exists(path); if (flag11) { File.AppendAllText(path, "{\"Rules\":[{\"CategoryName\":\"Default\",\"LogLevel\":\"Information\",\"LogType\":\"All\",\"TraceCount\":5}]}"); } ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); JsonConfigurationExtensions.AddJsonFile(FileConfigurationExtensions.SetBasePath(configurationBuilder, environment.ContentRootPath), path, true, true); IConfigurationRoot configuration = configurationBuilder.Build(); services.RemoveAll <ILoggerProviderConfigurationFactory>(); services.RemoveAll(typeof(ILoggerProviderConfiguration <>)); TypeInfo type = typeof(ILoggerProviderConfigurationFactory).Assembly.DefinedTypes.SingleOrDefault((TypeInfo t) => t.Name == "LoggingConfiguration"); services.RemoveAll(type); LoggingServiceCollectionExtensions.AddLogging(services, delegate(ILoggingBuilder x) { x.AddConfiguration(configuration); //bool flag13 = !x.Services.Any((ServiceDescriptor t) => t.ServiceType == typeof(ILoggerProvider)); //if (flag13) //{ // ConsoleLoggerExtensions.AddConsole(x); //} x.Services.RemoveAll <IConfigureOptions <LoggerFilterOptions> >(); x.Services.AddSingleton(new LoggerFilterConfigureOptions(configuration)); }); services.Replace(ServiceDescriptor.Singleton <ILoggerFactory, LoggerFactory>()); services.Replace(ServiceDescriptor.Singleton <DiagnosticSource>(new DefaultDiagnosticListener())); bool flag12 = services.IsHttpRequest(); if (flag12) { MarkdownFileMiddleware.SaveResourceFiles(environment.WebRootPath); } DefaultApplicationBuilderFactory.OnCreateBuilder(new Action <IApplicationBuilder, object>(LoggerExtensions.UseFileLog), logOptions); } return(services); }
// Internal for testing. internal static void AddRazorPagesServices(IServiceCollection services) { // Options services.TryAddEnumerable( ServiceDescriptor.Transient <IConfigureOptions <RazorViewEngineOptions>, RazorPagesRazorViewEngineOptionsSetup>()); services.TryAddEnumerable( ServiceDescriptor.Transient <IConfigureOptions <RazorPagesOptions>, RazorPagesOptionsSetup>()); // Routing services.TryAddEnumerable(ServiceDescriptor.Singleton <MatcherPolicy, DynamicPageEndpointMatcherPolicy>()); services.TryAddSingleton <DynamicPageEndpointSelectorCache>(); services.TryAddSingleton <PageActionEndpointDataSourceIdProvider>(); // Action description and invocation services.TryAddEnumerable( ServiceDescriptor.Singleton <IActionDescriptorProvider, CompiledPageActionDescriptorProvider>()); services.TryAddEnumerable( ServiceDescriptor.Singleton <IPageRouteModelProvider, CompiledPageRouteModelProvider>()); services.TryAddSingleton <PageActionEndpointDataSourceFactory>(); services.TryAddEnumerable(ServiceDescriptor.Singleton <MatcherPolicy, DynamicPageEndpointMatcherPolicy>()); services.TryAddEnumerable( ServiceDescriptor.Singleton <IPageApplicationModelProvider, DefaultPageApplicationModelProvider>()); services.TryAddEnumerable( ServiceDescriptor.Singleton <IPageApplicationModelProvider, AutoValidateAntiforgeryPageApplicationModelProvider>()); services.TryAddEnumerable( ServiceDescriptor.Singleton <IPageApplicationModelProvider, AuthorizationPageApplicationModelProvider>()); services.TryAddEnumerable( ServiceDescriptor.Singleton <IPageApplicationModelProvider, TempDataFilterPageApplicationModelProvider>()); services.TryAddEnumerable( ServiceDescriptor.Singleton <IPageApplicationModelProvider, ViewDataAttributePageApplicationModelProvider>()); services.TryAddEnumerable( ServiceDescriptor.Singleton <IPageApplicationModelProvider, ResponseCacheFilterApplicationModelProvider>()); services.TryAddSingleton <IPageApplicationModelPartsProvider, DefaultPageApplicationModelPartsProvider>(); services.TryAddEnumerable( ServiceDescriptor.Singleton <IActionInvokerProvider, PageActionInvokerProvider>()); services.TryAddEnumerable( ServiceDescriptor.Singleton <IRequestDelegateFactory, PageRequestDelegateFactory>()); services.TryAddSingleton <PageActionInvokerCache>(); // Page and Page model creation and activation services.TryAddSingleton <IPageModelActivatorProvider, DefaultPageModelActivatorProvider>(); services.TryAddSingleton <IPageModelFactoryProvider, DefaultPageModelFactoryProvider>(); services.TryAddSingleton <IPageActivatorProvider, DefaultPageActivatorProvider>(); services.TryAddSingleton <IPageFactoryProvider, DefaultPageFactoryProvider>(); #pragma warning disable CS0618 // Type or member is obsolete services.TryAddSingleton <IPageLoader>(s => s.GetRequiredService <PageLoader>()); #pragma warning restore CS0618 // Type or member is obsolete services.TryAddSingleton <PageLoader, DefaultPageLoader>(); services.TryAddSingleton <IPageHandlerMethodSelector, DefaultPageHandlerMethodSelector>(); // Action executors services.TryAddSingleton <PageResultExecutor>(); services.TryAddTransient <PageSaveTempDataPropertyFilter>(); }
/// <summary> /// /// </summary> /// <typeparam name="TService"></typeparam> /// <typeparam name="TImplementation"></typeparam> /// <param name="services"></param> /// <param name="serviceDescriptor"></param> /// <returns></returns> public static IServiceCollection ReplaceEnumerable <TService, TImplementation>(this IServiceCollection services, ServiceDescriptor serviceDescriptor) where TService : class where TImplementation : class, TService { return(services.ReplaceEnumerable(ServiceDescriptor.Transient <TService, TImplementation>(), serviceDescriptor)); }