// 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.Antiforgery; using Microsoft.AspNetCore.Antiforgery.Internal; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.ObjectPool; using Microsoft.Extensions.Options; namespace Microsoft.Extensions.DependencyInjection { /// /// Extension methods for setting up antiforgery services in an . /// public static class ServiceCollectionExtensions { /// /// Adds antiforgery services to the specified . /// /// The to add services to. public static void AddAntiforgery(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.AddDataProtection(); // Don't overwrite any options setups that a user may have added. services.TryAddEnumerable( ServiceDescriptor.Transient, AntiforgeryOptionsSetup>()); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddScoped(); services.TryAddSingleton(); services.TryAddSingleton(new DefaultObjectPoolProvider()); services.TryAddSingleton>(serviceProvider => { var provider = serviceProvider.GetRequiredService(); var policy = new AntiforgerySerializationContextPooledObjectPolicy(); return provider.Create(policy); }); } /// /// Adds antiforgery services to the specified . /// /// The to add services to. /// An to configure the provided . public static void AddAntiforgery(this IServiceCollection services, Action setupAction) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (setupAction == null) { throw new ArgumentNullException(nameof(setupAction)); } services.AddAntiforgery(); services.Configure(setupAction); } } }