Esempio n. 1
0
        /// <summary>
        /// Allows configurate the localization support from a single resource file
        /// </summary>
        /// <typeparam name="TClass">Type of the class used for find the localizated strings</typeparam>
        /// <typeparam name="TResource">Type of the resurce file used for find the localizated strings</typeparam>
        /// <param name="services">The application services collection</param>
        /// <param name="enviroment">The enviroment of the application</param>
        /// <returns>The modified application services collection</returns>
        public static IServiceCollection AddSingleLocalizationFile <TClass, TResource>(
            this IServiceCollection services, IHostingEnvironment enviroment)
        {
            if (!_isAddedServices)
            {
                throw new InvalidOperationException($"You should use the {nameof(AddLocalizationServices)} method first.");
            }

            var tClassType    = typeof(TClass);
            var tResourceType = typeof(TResource);

            if (!tClassType.Name.Equals(tResourceType.Name))
            {
                throw new ArgumentException($"The {nameof(TClass)} ({tClassType}) and the {nameof(TResource)} ({tResourceType}) types are not compatible.");
            }

            services.TryAddTransient(p =>
            {
                var stringLocalizer = p.GetService <IStringLocalizer <TClass> >();
                return(new SingleLocalizer(stringLocalizer, tResourceType));
            });

            services.TryAddTransient(p =>
            {
                var localizationOptions = p.GetService <IOptions <LocalizationOptions> >();
#if NETCOREAPP1_1
                var manager = new ResourceManagerStringLocalizerFactory(enviroment, localizationOptions);
#elif NETCOREAPP2_0
                var provider      = services.BuildServiceProvider();
                var loggerFactory = provider.GetService <ILoggerFactory>();
                var manager       = new ResourceManagerStringLocalizerFactory(localizationOptions, loggerFactory);
#endif
                var htmlLocalizer = new HtmlLocalizerFactory(manager).Create(tClassType);
                return(new SingleHtmlLocalizer(htmlLocalizer));
            });

            return(services);
        }
        protected virtual IStringLocalizer CreateStringLocalizer(string resourceName)
        {
            var resource = LocalizationOptions.Value.Resources.Values.FirstOrDefault(x => x.ResourceName == resourceName);

            return(HtmlLocalizerFactory.Create(resource != null ? resource.ResourceType : LocalizationOptions.Value.DefaultResourceType));
        }