// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Internal; using Microsoft.AspNetCore.Routing.Matching; using Microsoft.AspNetCore.Routing.Tree; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.ObjectPool; using Microsoft.Extensions.Options; namespace Microsoft.Extensions.DependencyInjection { /// /// Contains extension methods to . /// public static class RoutingServiceCollectionExtensions { /// /// Adds services required for routing requests. /// /// The to add the services to. /// The so that additional calls can be chained. public static IServiceCollection AddRouting(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.TryAddTransient(); services.TryAddSingleton>(s => { var provider = s.GetRequiredService(); return provider.Create(new UriBuilderContextPooledObjectPolicy()); }); // The TreeRouteBuilder is a builder for creating routes, it should stay transient because it's // stateful. services.TryAdd(ServiceDescriptor.Transient(s => { var loggerFactory = s.GetRequiredService(); var objectPool = s.GetRequiredService>(); var constraintResolver = s.GetRequiredService(); return new TreeRouteBuilder(loggerFactory, objectPool, constraintResolver); })); services.TryAddSingleton(typeof(RoutingMarkerService)); // Collect all data sources from DI. services.TryAddEnumerable(ServiceDescriptor.Transient, ConfigureEndpointOptions>()); // Allow global access to the list of endpoints. services.TryAddSingleton(s => { var options = s.GetRequiredService>(); return new CompositeEndpointDataSource(options.Value.DataSources); }); // // Endpoint Infrastructure // services.TryAddSingleton(); services.TryAddSingleton(); // // Default matcher implementation // services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddTransient(); // Link generation related services services.TryAddSingleton, RouteValuesBasedEndpointFinder>(); services.TryAddSingleton(); // // Endpoint Selection // services.TryAddSingleton(); services.TryAddEnumerable(ServiceDescriptor.Singleton()); return services; } /// /// Adds services required for routing requests. /// /// The to add the services to. /// The routing options to configure the middleware with. /// The so that additional calls can be chained. public static IServiceCollection AddRouting( this IServiceCollection services, Action configureOptions) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (configureOptions == null) { throw new ArgumentNullException(nameof(configureOptions)); } services.Configure(configureOptions); services.AddRouting(); return services; } } }