Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System.Reflection;
using System.Threading;

namespace BootstrapBlazor.Components;

Expand All @@ -18,7 +19,7 @@ internal class JsonStringLocalizerFactory : ResourceManagerStringLocalizerFactor
private readonly ILoggerFactory _loggerFactory;
private readonly JsonLocalizationOptions _jsonLocalizationOptions;
private readonly ILocalizationMissingItemHandler _localizationMissingItemHandler;
private string? _typeName;
private readonly AsyncLocal<string?> _typeName = new();

/// <summary>
/// <para lang="zh">构造函数</para>
Expand Down Expand Up @@ -81,7 +82,7 @@ protected override string GetResourcePrefix(TypeInfo typeInfo)
var index = typeName.IndexOf('`');
typeName = typeName[..index];
}
_typeName = typeName;
_typeName.Value = typeName;

return base.GetResourcePrefix(typeInfo);
}
Expand All @@ -96,7 +97,7 @@ protected override string GetResourcePrefix(string baseResourceName, string base
{
// https://gitee.com/LongbowEnterprise/BootstrapBlazor/issues/I5SRA1
var resourcePrefix = base.GetResourcePrefix(baseResourceName, baseNamespace);
_typeName = $"{baseNamespace}.{baseResourceName}";
_typeName.Value = $"{baseNamespace}.{baseResourceName}";

return resourcePrefix;
}
Expand All @@ -108,5 +109,10 @@ protected override string GetResourcePrefix(string baseResourceName, string base
/// </summary>
/// <param name="assembly"><para lang="zh">The assembly to create a <see cref="ResourceManagerStringLocalizer"/> for</para><para lang="en">The assembly to create a <see cref="ResourceManagerStringLocalizer"/> for</para></param>
/// <param name="baseName"><para lang="zh">The base name of the resource to search for</para><para lang="en">The base name of the resource to search for</para></param>
protected override ResourceManagerStringLocalizer CreateResourceManagerStringLocalizer(Assembly assembly, string baseName) => new JsonStringLocalizer(assembly, _typeName!, baseName, _jsonLocalizationOptions, _loggerFactory.CreateLogger<JsonStringLocalizer>(), ResourceNamesCache, _localizationMissingItemHandler);
protected override ResourceManagerStringLocalizer CreateResourceManagerStringLocalizer(Assembly assembly, string baseName)
{
var typeName = _typeName.Value ?? baseName;
_typeName.Value = null;
return new JsonStringLocalizer(assembly, typeName, baseName, _jsonLocalizationOptions, _loggerFactory.CreateLogger<JsonStringLocalizer>(), ResourceNamesCache, _localizationMissingItemHandler);
}
}
14 changes: 14 additions & 0 deletions test/UnitTest/Localization/JsonStringLocalizerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,20 @@ public void GetResourcePrefix_Ok()
Assert.Equal("test", result.Value);
}

[Fact]
public void CreateResourceManagerStringLocalizer_UseBaseNameWhenTypeNameIsNull()
{
var factory = Context.Services.GetRequiredService<IStringLocalizerFactory>();
var mi = factory.GetType().GetMethod("CreateResourceManagerStringLocalizer", BindingFlags.NonPublic | BindingFlags.Instance)!;

var baseName = typeof(Foo).FullName!;
var localizer = Assert.IsType<IStringLocalizer>(mi.Invoke(factory, [typeof(Foo).Assembly, baseName]), exactMatch: false);
var result = localizer["not-found-key"];

Assert.True(result.ResourceNotFound);
Comment on lines +334 to +343
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (testing): Add a test that covers reuse of the factory to ensure the AsyncLocal type name is cleared between invocations.

To also cover the new AsyncLocal behavior and the underlying concurrency bug, please add a test that calls CreateResourceManagerStringLocalizer twice: once after a GetResourcePrefix call (so _typeName is set) and then again without setting _typeName (or after clearing it). The second call should rely on baseName and must not reuse the previous type name, confirming that _typeName.Value is correctly reset and protecting against regressions in the cleanup logic.

Suggested implementation:

        Assert.Equal(baseName, result.SearchedLocation);
    }

    [Fact]
    public void CreateResourceManagerStringLocalizer_AsyncLocalTypeNameIsClearedBetweenInvocations()
    {
        var factory = Context.Services.GetRequiredService<IStringLocalizerFactory>();
        var factoryType = factory.GetType();

        var getResourcePrefix = factoryType.GetMethod(
            "GetResourcePrefix",
            BindingFlags.NonPublic | BindingFlags.Instance);

        var createLocalizer = factoryType.GetMethod(
            "CreateResourceManagerStringLocalizer",
            BindingFlags.NonPublic | BindingFlags.Instance)!;

        var fooType = typeof(Foo);
        var baseName = fooType.FullName!;

        // First invocation: simulate setting the AsyncLocal _typeName via GetResourcePrefix
        _ = getResourcePrefix!.Invoke(factory, new object[] { fooType });

        var localizer1 = Assert.IsType<IStringLocalizer>(
            createLocalizer.Invoke(factory, new object[] { fooType.Assembly, baseName }),
            exactMatch: false);

        var firstResult = localizer1["not-found-key"];
        Assert.True(firstResult.ResourceNotFound);

        // Second invocation without setting _typeName again. This must rely solely on baseName
        // and must not reuse the previous AsyncLocal type name.
        var localizer2 = Assert.IsType<IStringLocalizer>(
            createLocalizer.Invoke(factory, new object[] { fooType.Assembly, baseName }),
            exactMatch: false);

        var secondResult = localizer2["not-found-key"];

        Assert.True(secondResult.ResourceNotFound);
        Assert.Equal(baseName, secondResult.SearchedLocation);
    }

This test assumes:

  1. The factory under test exposes a non-public instance method named GetResourcePrefix that accepts a single Type (or compatible) parameter. If the actual signature differs (e.g., TypeInfo), adjust the Invoke call accordingly, for example:
    • new object[] { fooType.GetTypeInfo() } for a TypeInfo parameter.
  2. using System.Reflection; and using Microsoft.Extensions.Localization; are already present at the top of the file.
    If the method name or binding flags differ in your implementation, update the reflection calls to match the actual factory API.

Assert.Equal(baseName, result.SearchedLocation);
}

Copy link

Copilot AI Apr 27, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change fixes a concurrency issue in the localizer factory, but there isn’t a regression test that exercises concurrent IStringLocalizerFactory.Create(...) calls (e.g., in parallel tasks) to ensure SearchedLocation/type resolution doesn’t bleed across requests. Adding a small parallel test would help prevent this from reappearing.

Suggested change
[Fact]
public async Task Create_Ok_InParallel()
{
var factory = Context.Services.GetRequiredService<IStringLocalizerFactory>();
var expectedNamedSearchedLocation = factory.Create("Lang", "UnitTest")["not-found-key"].SearchedLocation;
var expectedTypedSearchedLocation = factory.Create(typeof(Foo))["not-found-key"].SearchedLocation;
var tasks = Enumerable.Range(0, 50).Select(async index =>
{
await Task.Yield();
if (index % 2 == 0)
{
var localizer = factory.Create("Lang", "UnitTest");
var result = localizer[$"not-found-key-{index}"];
Assert.True(result.ResourceNotFound);
Assert.Equal(expectedNamedSearchedLocation, result.SearchedLocation);
}
else
{
var localizer = factory.Create(typeof(Foo));
var result = localizer[$"not-found-key-{index}"];
Assert.True(result.ResourceNotFound);
Assert.Equal(expectedTypedSearchedLocation, result.SearchedLocation);
}
});
await Task.WhenAll(tasks);
}

Copilot uses AI. Check for mistakes.
private static readonly string[] localizationConfigure = ["zh-CN.json"];

[Fact]
Expand Down
Loading