< Summary

Information
Class: MyNet.Humanizer.ServiceCollectionExtensions
Assembly: MyNet.Humanizer
File(s): https://raw.githubusercontent.com/sandre58/MyNet/85372080fe102cd9ee155ceab49ae000e7f66103/src/MyNet.Humanizer/Extensions/ServiceCollectionExtensions.cs
Tag: 323_28699572109
Line coverage
100%
Covered lines: 44
Uncovered lines: 0
Coverable lines: 44
Total lines: 148
Line coverage: 100%
Branch coverage
75%
Covered branches: 3
Total branches: 4
Branch coverage: 75%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
AddHumanizer(...)50%22100%
AddDisplayTextStrategy(...)100%22100%
AddDisplayTextInfrastructure(...)100%11100%
UseDisplayText(...)100%11100%

File(s)

https://raw.githubusercontent.com/sandre58/MyNet/85372080fe102cd9ee155ceab49ae000e7f66103/src/MyNet.Humanizer/Extensions/ServiceCollectionExtensions.cs

#LineLine coverage
 1// -----------------------------------------------------------------------
 2// <copyright file="ServiceCollectionExtensions.cs" company="Stéphane ANDRE">
 3// Copyright (c) Stéphane ANDRE. All rights reserved.
 4// </copyright>
 5// -----------------------------------------------------------------------
 6
 7using System;
 8using System.Linq;
 9using Microsoft.Extensions.DependencyInjection;
 10using Microsoft.Extensions.DependencyInjection.Extensions;
 11using MyNet.Globalization;
 12using MyNet.Globalization.Culture;
 13using MyNet.Globalization.Localization.Providers;
 14using MyNet.Globalization.Localization.Translation;
 15using MyNet.Humanizer.Display;
 16using MyNet.Humanizer.Display.Registration;
 17using MyNet.Humanizer.Display.Strategies;
 18using MyNet.Humanizer.Facade;
 19using MyNet.Humanizer.Formatting.Addresses;
 20using MyNet.Humanizer.Formatting.Addresses.Cultures;
 21using MyNet.Humanizer.Formatting.Collections;
 22using MyNet.Humanizer.Ordinalizing;
 23using MyNet.Humanizer.Ordinalizing.Cultures;
 24using MyNet.Humanizer.Resources;
 25using MyNet.Humanizer.Temporal;
 26using MyNet.Primitives;
 27
 28#pragma warning disable IDE0130 // Namespace does not match folder structure
 29namespace MyNet.Humanizer;
 30#pragma warning restore IDE0130 // Namespace does not match folder structure
 31
 32/// <summary>
 33/// Dependency injection extensions for registering humanizer providers.
 34/// Call this after AddLocalization().
 35/// </summary>
 36public static class ServiceCollectionExtensions
 37{
 38    extension(IServiceCollection services)
 39    {
 40        /// <summary>
 41        /// Adds humanizer services to the service collection.
 42        /// This method registers humanizer resources and providers into the localization system.
 43        /// </summary>
 44        /// <param name="configure">An action to configure the time localization options.</param>
 45        /// <returns>The updated service collection.</returns>
 46        public IServiceCollection AddHumanizer(Action<TimeLocalizationOptions>? configure = null)
 47        {
 1448            ArgumentNullException.ThrowIfNull(services);
 49
 1450            var options = new TimeLocalizationOptions();
 1451            configure?.Invoke(options);
 52
 53            // Ensure Localization infrastructure is loaded before registering humanizer services, as some providers dep
 1454            services.AddLocalization();
 55
 56            // List formatters
 1457            services.AddLocalizationService<IListFormatter>((sp, culture) => new ListFormatter(sp.GetRequiredService<ITr
 58
 59            // DateTime providers
 60            // Uses LocalizationServiceContext to resolve IListFormatter for the same culture without repeating it.
 1461            services.AddLocalizationService<ITimeHumanizer>((sp, culture) => new TimeHumanizer(
 1462                sp.GetRequiredService<ITranslationService>(),
 1463                sp.GetRequiredService<ICultureScopedServiceSource<IListFormatter>>(),
 1464                culture,
 1465                options));
 66
 67            // Ordinalizers
 1468            services.AddLocalizationService<IOrdinalizer>((_, _) => Ordinalizers.Invariant);
 1469            services.ConfigureLocalizationService<IOrdinalizer>(builder => builder
 1470                .RegisterCulture(SupportedCultures.English, () => Ordinalizers.English)
 1471                .RegisterCulture(SupportedCultures.French, () => Ordinalizers.French));
 72
 73            // Address formatters
 1474            services.AddLocalizationService<IAddressFormatter>((_, _) => AddressFormatters.Invariant);
 1475            services.ConfigureLocalizationService<IAddressFormatter>(builder => builder
 1476                .RegisterCulture(SupportedCultures.English, () => AddressFormatters.English)
 1477                .RegisterCulture(SupportedCultures.French, () => AddressFormatters.French));
 78
 79            // Resources
 1480            services.AddTranslationResource(nameof(DateTimeResources), DateTimeResources.ResourceManager);
 1481            services.AddTranslationResource(nameof(EnumResources), EnumResources.ResourceManager);
 1482            services.AddTranslationResource(nameof(ListResources), ListResources.ResourceManager);
 83
 84            // DisplayText providers
 1485            services.AddDisplayTextInfrastructure();
 1486            services.AddDisplayTextStrategy<Enum, EnumDisplayTextStrategy>();
 1487            services.AddDisplayTextStrategy<ISmartEnum, SmartEnumDisplayTextStrategy>();
 88
 1489            return services;
 90        }
 91
 92        /// <summary>
 93        /// Adds a display text strategy for the specified type and strategy implementation. This method registers the s
 94        /// </summary>
 95        /// <typeparam name="T">The target type for which the display text strategy is registered.</typeparam>
 96        /// <typeparam name="TStrategy">The display text strategy implementation.</typeparam>
 97        /// <returns>The updated service collection.</returns>
 98        public IServiceCollection AddDisplayTextStrategy<T, TStrategy>()
 99            where T : notnull
 100            where TStrategy : class, IDisplayTextStrategy<T>
 101        {
 58102            services.AddLocalization();
 58103            services.AddDisplayTextInfrastructure();
 104
 58105            services.TryAddSingleton<TStrategy>();
 106
 107            // Register the non-generic marker so the registry can discover all factories.
 108            // We use AddSingleton (not TryAddEnumerable) because TryAddEnumerable requires
 109            // a concrete implementation type for deduplication, which factory-delegate descriptors lack.
 58110            services.TryAddSingleton<IDisplayTextStrategy<T>, TStrategy>();
 58111            services.AddSingleton<IDisplayTextStrategyRegistration>(sp => new DisplayTextStrategyRegistration<T>(sp.GetR
 112
 58113            return services;
 114        }
 115
 116        /// <summary>
 117        /// Adds the necessary infrastructure for display text providers, including the registry and resolver.
 118        /// </summary>
 119        private void AddDisplayTextInfrastructure()
 120        {
 72121            services.TryAddSingleton<IDisplayTextStrategyRegistry>(sp =>
 72122            {
 72123                var registrations = sp.GetServices<IDisplayTextStrategyRegistration>();
 72124
 72125                var dictionary = registrations.ToDictionary(x => x.TargetType, x => x.Strategy);
 72126
 72127                return new DisplayTextStrategyRegistry(dictionary);
 72128            });
 72129            services.TryAddSingleton<IDisplayTextStrategyResolver, DisplayTextStrategyResolver>();
 72130            services.TryAddSingleton<IDisplayTextService, DisplayTextService>();
 72131        }
 132    }
 133
 134    extension(IServiceProvider serviceProvider)
 135    {
 136        /// <summary>
 137        /// Configures the static Humanizer class to use the IDisplayTextService from the service provider. This method 
 138        /// </summary>
 139        /// <returns>The updated service provider.</returns>
 140        public IServiceProvider UseDisplayText()
 141        {
 8142            TextHumanizer.Configure(serviceProvider.GetRequiredService<IDisplayTextService>());
 143
 8144            return serviceProvider;
 145        }
 146    }
 147}
 148