// 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 System.Text.Encodings.Web;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.WebEncoders;
namespace Microsoft.Extensions.DependencyInjection
{
///
/// Extension methods for setting up web encoding services in an .
///
public static class EncoderServiceCollectionExtensions
{
///
/// Adds , and
/// to the specified .
///
/// The .
/// The so that additional calls can be chained.
public static IServiceCollection AddWebEncoders(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
services.AddOptions();
// Register the default encoders
// We want to call the 'Default' property getters lazily since they perform static caching
services.TryAddSingleton(
CreateFactory(() => HtmlEncoder.Default, settings => HtmlEncoder.Create(settings)));
services.TryAddSingleton(
CreateFactory(() => JavaScriptEncoder.Default, settings => JavaScriptEncoder.Create(settings)));
services.TryAddSingleton(
CreateFactory(() => UrlEncoder.Default, settings => UrlEncoder.Create(settings)));
return services;
}
///
/// Adds , and
/// to the specified .
///
/// The .
/// An to configure the provided .
/// The so that additional calls can be chained.
public static IServiceCollection AddWebEncoders(this IServiceCollection services, Action setupAction)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
if (setupAction == null)
{
throw new ArgumentNullException(nameof(setupAction));
}
services.AddWebEncoders();
services.Configure(setupAction);
return services;
}
private static Func CreateFactory(
Func defaultFactory,
Func customSettingsFactory)
{
return serviceProvider =>
{
var settings = serviceProvider
?.GetService>()
?.Value
?.TextEncoderSettings;
return (settings != null) ? customSettingsFactory(settings) : defaultFactory();
};
}
}
}