// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Routing; using Microsoft.Framework.Internal; namespace Microsoft.Framework.DependencyInjection { public static class MvcServiceCollectionExtensions { public static IServiceCollection AddMvc([NotNull] this IServiceCollection services) { ConfigureDefaultServices(services); services.TryAdd(MvcServices.GetDefaultServices()); return services; } /// /// Configures a set of for the application. /// /// The services available in the application. /// The which need to be configured. public static void ConfigureMvc( [NotNull] this IServiceCollection services, [NotNull] Action setupAction) { services.Configure(setupAction); } /// /// Register the specified as services and as a source for controller /// discovery. /// /// The . /// A sequence of controller s to register in the /// and used for controller discovery. /// The . public static IServiceCollection WithControllersAsServices( [NotNull] this IServiceCollection services, [NotNull] IEnumerable controllerTypes) { var controllerTypeProvider = new FixedSetControllerTypeProvider(); foreach (var type in controllerTypes) { services.AddTransient(type); controllerTypeProvider.ControllerTypes.Add(type.GetTypeInfo()); } services.Replace(ServiceDescriptor.Transient()); services.Replace(ServiceDescriptor.Instance(controllerTypeProvider)); return services; } /// /// Registers controller types from the specified as services and as a source /// for controller discovery. /// /// The . /// Assemblies to scan. /// The . public static IServiceCollection WithControllersAsServices( [NotNull] this IServiceCollection services, [NotNull] IEnumerable controllerAssemblies) { var assemblyProvider = new FixedSetAssemblyProvider(); foreach (var assembly in controllerAssemblies) { assemblyProvider.CandidateAssemblies.Add(assembly); } var controllerTypeProvider = new DefaultControllerTypeProvider(assemblyProvider); var controllerTypes = controllerTypeProvider.ControllerTypes; return WithControllersAsServices(services, controllerTypes.Select(type => type.AsType())); } private static void ConfigureDefaultServices(IServiceCollection services) { services.AddOptions(); services.AddDataProtection(); services.AddRouting(); services.AddCors(); services.AddAuthorization(); services.AddWebEncoders(); services.Configure( routeOptions => routeOptions.ConstraintMap.Add("exists", typeof(KnownRouteValueConstraint))); } } }