Skip to content

Commit

Permalink
Overriding thread culture correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
johnknoop committed Feb 19, 2020
1 parent 5b64713 commit a554f94
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
31 changes: 24 additions & 7 deletions source/Consume/MessageHandlerBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,25 @@ private void DoSubscribe(CancellationToken? cancelled = null, Func<IDisposable>

private async Task HandleMessageReceived(CancellationToken? cancelled, Message message, Func<IDisposable> blockInterruption, IReceiverClient client)
{
(bool cultureOverridden, CultureInfo defaultCulture, CultureInfo defaultUiCulture) TryOverrideCulture()
{
var cultureOverridden = false;
var defaultCulture = CultureInfo.CurrentCulture;
var defaultUiCulture = CultureInfo.CurrentUICulture;

if (_setCulture && message.UserProperties.ContainsKey("Culture") && message.UserProperties["Culture"] != null)
{
var culture = CultureInfo.GetCultureInfo((string) message.UserProperties["Culture"]);

CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = culture;

cultureOverridden = true;
}

return (cultureOverridden, defaultCulture, defaultUiCulture);
}

if (cancelled?.IsCancellationRequested == true)
{
await client.AbandonAsync(message.SystemProperties.LockToken);
Expand All @@ -342,13 +361,10 @@ private async Task HandleMessageReceived(CancellationToken? cancelled, Message m

using (blockInterruption())
{
var (cultureOverridden, defaultCulture, defaultUiCulture) = TryOverrideCulture();

try
{
if (_setCulture && message.UserProperties.ContainsKey("Culture"))
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo((string)message.UserProperties["Culture"]);
}

_services?.AddScoped(provider => message);

if (message.UserProperties.TryGetValue("MessageType", out var messageType) &&
Expand Down Expand Up @@ -388,9 +404,10 @@ private async Task HandleMessageReceived(CancellationToken? cancelled, Message m
}
finally
{
if (_setCulture)
if (cultureOverridden)
{
CultureInfo.CurrentCulture = CultureInfo.DefaultThreadCurrentCulture;
CultureInfo.CurrentCulture = defaultCulture;
CultureInfo.CurrentUICulture = defaultUiCulture;
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion source/TinyDancer.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<PackageTags>azure servicebus service bus message queue</PackageTags>
<PackageProjectUrl>https://github.com/johnknoop/TinyDancer</PackageProjectUrl>
<RepositoryUrl>https://github.com/johnknoop/TinyDancer</RepositoryUrl>
<Version>2.0.0-rc.6</Version>
<Version>2.0.0-rc.7</Version>
</PropertyGroup>

<ItemGroup>
Expand Down

0 comments on commit a554f94

Please sign in to comment.