Allow to create stringlocalizer by resource name instead of resource type

pull/13845/head
Halil İbrahim Kalkan 3 years ago
parent c05a4b04b6
commit 614512d1f1

@ -4,7 +4,15 @@ public static class AbpStringLocalizerFactoryExtensions
{
public static IStringLocalizer CreateDefaultOrNull(this IStringLocalizerFactory localizerFactory)
{
return (localizerFactory as IAbpStringLocalizerFactoryWithDefaultResourceSupport)
return (localizerFactory as IAbpStringLocalizerFactory)
?.CreateDefaultOrNull();
}
public static IStringLocalizer CreateByResourceNameOrNull(
this IStringLocalizerFactory localizerFactory,
string resourceName)
{
return (localizerFactory as IAbpStringLocalizerFactory)
?.CreateByResourceNameOrNull(resourceName);
}
}

@ -2,8 +2,11 @@
namespace Microsoft.Extensions.Localization;
public interface IAbpStringLocalizerFactoryWithDefaultResourceSupport
public interface IAbpStringLocalizerFactory
{
[CanBeNull]
IStringLocalizer CreateDefaultOrNull();
[CanBeNull]
IStringLocalizer CreateByResourceNameOrNull([NotNull] string resourceName);
}

@ -9,7 +9,7 @@ using Microsoft.Extensions.Options;
namespace Volo.Abp.Localization;
public class AbpStringLocalizerFactory : IStringLocalizerFactory, IAbpStringLocalizerFactoryWithDefaultResourceSupport
public class AbpStringLocalizerFactory : IStringLocalizerFactory, IAbpStringLocalizerFactory
{
protected internal AbpLocalizationOptions AbpLocalizationOptions { get; }
protected ResourceManagerStringLocalizerFactory InnerFactory { get; }
@ -37,6 +37,22 @@ public class AbpStringLocalizerFactory : IStringLocalizerFactory, IAbpStringLoca
return InnerFactory.Create(resourceType);
}
return CreateInternal(resourceType, resource);
}
public IStringLocalizer CreateByResourceNameOrNull(string resourceName)
{
var resource = AbpLocalizationOptions.Resources.GetOrNull(resourceName);
if (resource == null)
{
return null;
}
return CreateInternal(resource.ResourceType, resource);
}
private IStringLocalizer CreateInternal(Type resourceType, LocalizationResource resource)
{
if (LocalizerCache.TryGetValue(resourceType, out var cacheItem))
{
return cacheItem.Localizer;

@ -0,0 +1,34 @@
using Microsoft.Extensions.Localization;
using Shouldly;
using Volo.Abp.DynamicProxy;
using Volo.Abp.Testing;
using Xunit;
namespace Volo.Abp.Localization;
public class AbpStringLocalizerFactory_Tests : AbpIntegratedTest<AbpLocalizationTestModule>
{
private readonly IStringLocalizerFactory _factory;
public AbpStringLocalizerFactory_Tests()
{
_factory = GetRequiredService<IStringLocalizerFactory>();
}
[Fact]
public void Factory_Type_Should_Be_AbpStringLocalizerFactory()
{
ProxyHelper.UnProxy(_factory).ShouldBeOfType<AbpStringLocalizerFactory>();
}
[Fact]
public void Should_Create_Resource_By_Name()
{
using (CultureHelper.Use("en"))
{
var localizer = _factory.CreateByResourceNameOrNull("Test");
localizer.ShouldNotBeNull();
localizer["CarPlural"].Value.ShouldBe("Cars");
}
}
}
Loading…
Cancel
Save