Skip to content

Commit

Permalink
added strongly typed API
Browse files Browse the repository at this point in the history
  • Loading branch information
Jukka Snellman committed Aug 16, 2022
1 parent 32336e6 commit 5b96ddf
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ public void GetString_Missing()
Translate("Missing", CultureInfo.GetCultureInfo("en-US")).ResourceNotFound.Should().BeTrue();
}

[Fact]
public void GetString_Typed()
{
var localizer = _factory.Create<MyClass>(CultureInfo.InvariantCulture);
localizer["Hello"].Value.Should().Be("Hello World");
}

}

class MyClass
Expand Down
21 changes: 11 additions & 10 deletions StringLocalizerWithCulture/StringLocalizerWithCultureFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ namespace StringLocalizerWithCulture
public interface IStringLocalizerWithCultureFactory
{
IStringLocalizer Create(Type resourceSource, CultureInfo culture);
IStringLocalizer<T> Create<T>(CultureInfo culture);
}

// Adapted from https://github.com/dotnet/aspnetcore/issues/7756
Expand All @@ -32,27 +33,27 @@ public StringLocalizerWithCultureFactory(
private readonly ConcurrentDictionary<string, StringLocalizerWithCulture> _localizerCache
= new ConcurrentDictionary<string, StringLocalizerWithCulture>();

public IStringLocalizer Create(Type resourceSource, CultureInfo culture)
{
if (resourceSource == null)
{
throw new ArgumentNullException(nameof(resourceSource));
}
public IStringLocalizer Create(Type resourceSource, CultureInfo culture)
=> CreateResourceManagerStringLocalizer<object>(resourceSource, culture);

public IStringLocalizer<T> Create<T>(CultureInfo culture) => CreateResourceManagerStringLocalizer<T>(typeof(T), culture);

private StringLocalizerWithCulture<T> CreateResourceManagerStringLocalizer<T>(Type resourceSource,
CultureInfo culture)
{
var typeInfo = resourceSource.GetTypeInfo();
var baseName = GetResourcePrefix(typeInfo);
var assembly = typeInfo.Assembly;

return _localizerCache.GetOrAdd(baseName, _ => CreateResourceManagerStringLocalizer(assembly, baseName, culture));
return (StringLocalizerWithCulture<T>)_localizerCache.GetOrAdd(baseName, _ => CreateResourceManagerStringLocalizer<T>(assembly, baseName, culture));
}

private StringLocalizerWithCulture CreateResourceManagerStringLocalizer(
private StringLocalizerWithCulture<T> CreateResourceManagerStringLocalizer<T>(
Assembly assembly,
string baseName,
CultureInfo culture)
{
var resources = new ResourceManager(baseName, assembly);
return new StringLocalizerWithCulture(resources, assembly, baseName, _resourceNamesCache,
return new StringLocalizerWithCulture<T>(resources, assembly, baseName, _resourceNamesCache,
_loggerFactory.CreateLogger<ResourceManagerStringLocalizer>(),
culture);
}
Expand Down

0 comments on commit 5b96ddf

Please sign in to comment.