Skip to content

Commit 203caa0

Browse files
committed
React to more changes
1 parent 4493d07 commit 203caa0

22 files changed

+145
-95
lines changed

src/Components/Blazor/Blazor/src/Hosting/WebAssemblyHost.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ public Task StartAsync(CancellationToken cancellationToken = default)
3838
// this happens in the browser it will be a direct call from Mono. We effectively needs to set the
3939
// JSRuntime in the 'root' execution context which implies that we want to do as part of a direct
4040
// call from Program.Main, and before any 'awaits'.
41-
JSRuntime.SetCurrentJSRuntime(_runtime);
4241
SetBrowserHttpMessageHandlerAsDefault();
4342

4443
return StartAsyncAwaited();

src/Components/Blazor/Blazor/src/Microsoft.AspNetCore.Blazor.csproj

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
<Project Sdk="Microsoft.NET.Sdk">
1+
<Project Sdk="Microsoft.NET.Sdk">
22

33
<PropertyGroup>
44
<TargetFramework>netstandard2.0</TargetFramework>
@@ -13,9 +13,11 @@
1313
</ItemGroup>
1414

1515
<ItemGroup>
16-
<Compile Include="..\..\..\Shared\src\BrowserNavigationManagerInterop.cs" />
17-
<Compile Include="..\..\..\Shared\src\JsonSerializerOptionsProvider.cs" />
18-
<Compile Include="..\..\..\Shared\src\WebEventData.cs" />
16+
<Compile Include="$(ComponentsSharedSourceRoot)src\BrowserNavigationManagerInterop.cs" />
17+
<Compile Include="$(ComponentsSharedSourceRoot)src\JsonSerializerOptionsProvider.cs" />
18+
<Compile Include="$(ComponentsSharedSourceRoot)src\WebEventData.cs" />
19+
20+
<Compile Include="$(ComponentsSharedSourceRoot)src\ElementReferenceJsonConverter.cs" />
1921
</ItemGroup>
2022

2123
</Project>
Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,34 @@
11
// Copyright (c) .NET Foundation. All rights reserved.
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

4+
using Microsoft.AspNetCore.Components;
45
using Mono.WebAssembly.Interop;
56

67
namespace Microsoft.AspNetCore.Blazor.Services
78
{
8-
internal static class WebAssemblyJSRuntime
9+
internal sealed class WebAssemblyJSRuntime : MonoWebAssemblyJSRuntime
910
{
10-
public static readonly MonoWebAssemblyJSRuntime Instance = new MonoWebAssemblyJSRuntime();
11+
private static readonly WebAssemblyJSRuntime _instance = new WebAssemblyJSRuntime();
12+
private static bool _initialized;
13+
14+
public WebAssemblyJSRuntime()
15+
{
16+
JsonSerializerOptions.Converters.Add(new ElementReferenceJsonConverter());
17+
}
18+
19+
public static WebAssemblyJSRuntime Instance
20+
{
21+
get
22+
{
23+
if (!_initialized)
24+
{
25+
// This is executing in MonoWASM. Consequently we do not to have concern ourselves with thread safety.
26+
_initialized = true;
27+
Initialize(_instance);
28+
}
29+
30+
return _instance;
31+
}
32+
}
1133
}
1234
}

src/Components/Blazor/Build/test/GenericComponentRazorIntegrationTest.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ public void Render_GenericComponent_WithRef()
120120
AdditionalSyntaxTrees.Add(GenericContextComponent);
121121

122122
var component = CompileToComponent(@"
123-
<GenericContext TItem=int Items=""@(new List<int>() { 1, 2, })"" @ref=""_my"" @ref:suppressField />
123+
<GenericContext TItem=int Items=""@(new List<int>() { 1, 2, })"" @ref=""_my"" />
124124
125125
@code {
126126
GenericContext<int> _my;
@@ -187,7 +187,7 @@ public void Render_GenericComponent_TypeInference_WithRef()
187187
AdditionalSyntaxTrees.Add(GenericContextComponent);
188188

189189
var component = CompileToComponent(@"
190-
<GenericContext Items=""@(new List<int>() { 1, 2, })"" @ref=""_my"" @ref:suppressField />
190+
<GenericContext Items=""@(new List<int>() { 1, 2, })"" @ref=""_my"" />
191191
192192
@code {
193193
GenericContext<int> _my;
@@ -220,7 +220,7 @@ public void Render_GenericComponent_TypeInference_WithRef_Recursive()
220220

221221
var assembly = CompileToAssembly("Test.cshtml", @"
222222
@typeparam TItem
223-
<GenericContext Items=""@MyItems"" @ref=""_my"" @ref:suppressField />
223+
<GenericContext Items=""@MyItems"" @ref=""_my"" />
224224
225225
@code {
226226
[Parameter] public List<TItem> MyItems { get; set; }

src/Components/Components/ref/Microsoft.AspNetCore.Components.csproj

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,12 @@
55
</PropertyGroup>
66
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
77
<Compile Include="Microsoft.AspNetCore.Components.netstandard2.0.cs" />
8-
<Reference Include="Microsoft.JSInterop" />
98
<Reference Include="Microsoft.Extensions.Logging.Abstractions" />
109
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
10+
<Reference Include="System.Buffers" />
1111
</ItemGroup>
1212
<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.0'">
1313
<Compile Include="Microsoft.AspNetCore.Components.netcoreapp3.0.cs" />
14-
<Reference Include="Microsoft.JSInterop" />
1514
<Reference Include="Microsoft.Extensions.Logging.Abstractions" />
1615
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
1716
</ItemGroup>

src/Components/Components/ref/Microsoft.AspNetCore.Components.netcoreapp3.0.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,8 @@ protected void OnUnhandledException(System.UnhandledExceptionEventArgs e) { }
110110
public readonly partial struct ElementReference
111111
{
112112
private readonly object _dummy;
113+
public ElementReference(string id) { throw null; }
114+
public string Id { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
113115
}
114116
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
115117
public readonly partial struct EventCallback

src/Components/Components/ref/Microsoft.AspNetCore.Components.netstandard2.0.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,8 @@ protected void OnUnhandledException(System.UnhandledExceptionEventArgs e) { }
110110
public readonly partial struct ElementReference
111111
{
112112
private readonly object _dummy;
113+
public ElementReference(string id) { throw null; }
114+
public string Id { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } }
113115
}
114116
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
115117
public readonly partial struct EventCallback

src/Components/Components/src/ElementReference.cs

Lines changed: 2 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,13 @@
33

44
using System;
55
using System.Globalization;
6-
using System.Text.Json;
7-
using System.Text.Json.Serialization;
86
using System.Threading;
97

108
namespace Microsoft.AspNetCore.Components
119
{
1210
/// <summary>
1311
/// Represents a reference to a rendered element.
1412
/// </summary>
15-
[JsonConverter(typeof(ElementReferenceConverter))]
1613
public readonly struct ElementReference
1714
{
1815
private static long _nextIdForWebAssemblyOnly = 1;
@@ -24,9 +21,9 @@ public readonly struct ElementReference
2421
/// The Id is unique at least within the scope of a given user/circuit.
2522
/// This property is public to support Json serialization and should not be used by user code.
2623
/// </remarks>
27-
internal string Id { get; }
24+
public string Id { get; }
2825

29-
private ElementReference(string id)
26+
public ElementReference(string id)
3027
{
3128
Id = id;
3229
}
@@ -54,48 +51,5 @@ private static string CreateUniqueId()
5451
return Guid.NewGuid().ToString("D", CultureInfo.InvariantCulture);
5552
}
5653
}
57-
58-
private sealed class ElementReferenceConverter : JsonConverter<ElementReference>
59-
{
60-
private static readonly JsonEncodedText IdProperty = JsonEncodedText.Encode("__internalId");
61-
62-
public override ElementReference Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
63-
{
64-
string id = null;
65-
while (reader.Read() && reader.TokenType != JsonTokenType.EndObject)
66-
{
67-
if (reader.TokenType == JsonTokenType.PropertyName)
68-
{
69-
if (reader.ValueTextEquals(IdProperty.EncodedUtf8Bytes))
70-
{
71-
reader.Read();
72-
id = reader.GetString();
73-
}
74-
else
75-
{
76-
throw new JsonException($"Unexpected JSON property '{reader.GetString()}'.");
77-
}
78-
}
79-
else
80-
{
81-
throw new JsonException($"Unexcepted JSON Token {reader.TokenType}.");
82-
}
83-
}
84-
85-
if (id is null)
86-
{
87-
throw new JsonException("__internalId is required.");
88-
}
89-
90-
return new ElementReference(id);
91-
}
92-
93-
public override void Write(Utf8JsonWriter writer, ElementReference value, JsonSerializerOptions options)
94-
{
95-
writer.WriteStartObject();
96-
writer.WriteString(IdProperty, value.Id);
97-
writer.WriteEndObject();
98-
}
99-
}
10054
}
10155
}

src/Components/Components/src/Microsoft.AspNetCore.Components.csproj

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,18 @@
1010
</PropertyGroup>
1111

1212
<ItemGroup>
13-
<Compile Include="..\..\Shared\src\JsonSerializerOptionsProvider.cs" />
1413
<Compile Include="$(ComponentsSharedSourceRoot)src\ArrayBuilder.cs" LinkBase="RenderTree" />
1514
</ItemGroup>
1615

1716
<ItemGroup>
18-
<Reference Include="Microsoft.JSInterop" />
1917
<Reference Include="Microsoft.Extensions.Logging.Abstractions" />
2018
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
2119
</ItemGroup>
2220

21+
<ItemGroup Condition="'$(TargetFramework)'=='netstandard2.0'">
22+
<Reference Include="System.Buffers" />
23+
</ItemGroup>
24+
2325
<Target Name="_GetNuspecDependencyPackageVersions">
2426
<MSBuild Targets="_GetPackageVersionInfo"
2527
BuildInParallel="$(BuildInParallel)"

src/Components/Server/src/Circuits/CircuitHost.cs

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
using Microsoft.AspNetCore.SignalR;
1313
using Microsoft.Extensions.DependencyInjection;
1414
using Microsoft.Extensions.Logging;
15-
using Microsoft.JSInterop;
1615
using Microsoft.JSInterop.Infrastructure;
1716

1817
namespace Microsoft.AspNetCore.Components.Server.Circuits
@@ -26,11 +25,6 @@ internal class CircuitHost : IAsyncDisposable
2625
private bool _initialized;
2726
private bool _disposed;
2827

29-
/// <summary>
30-
/// Sets the <see cref="IJSRuntime"/> for the current excution context.
31-
/// </summary>
32-
public void SetCurrentJSRuntime() => JSInterop.JSRuntime.SetCurrentJSRuntime(JSRuntime);
33-
3428
// This event is fired when there's an unrecoverable exception coming from the circuit, and
3529
// it need so be torn down. The registry listens to this even so that the circuit can
3630
// be torn down even when a client is not connected.
@@ -101,7 +95,6 @@ public Task InitializeAsync(CancellationToken cancellationToken)
10195

10296
try
10397
{
104-
SetCurrentJSRuntime();
10598
_initialized = true; // We're ready to accept incoming JSInterop calls from here on
10699

107100
await OnCircuitOpenedAsync(cancellationToken);
@@ -341,9 +334,8 @@ public async Task BeginInvokeDotNetFromJS(string callId, string assemblyName, st
341334
{
342335
await Renderer.Dispatcher.InvokeAsync(() =>
343336
{
344-
SetCurrentJSRuntime();
345337
Log.BeginInvokeDotNet(_logger, callId, assemblyName, methodIdentifier, dotNetObjectId);
346-
DotNetDispatcher.BeginInvokeDotNet(callId, assemblyName, methodIdentifier, dotNetObjectId, argsJson);
338+
DotNetDispatcher.BeginInvokeDotNet(JSRuntime, callId, assemblyName, methodIdentifier, dotNetObjectId, argsJson);
347339
});
348340
}
349341
catch (Exception ex)
@@ -367,7 +359,6 @@ public async Task EndInvokeJSFromDotNet(long asyncCall, bool succeded, string ar
367359
{
368360
await Renderer.Dispatcher.InvokeAsync(() =>
369361
{
370-
SetCurrentJSRuntime();
371362
if (!succeded)
372363
{
373364
// We can log the arguments here because it is simply the JS error with the call stack.
@@ -378,7 +369,7 @@ await Renderer.Dispatcher.InvokeAsync(() =>
378369
Log.EndInvokeJSSucceeded(_logger, asyncCall);
379370
}
380371

381-
DotNetDispatcher.EndInvokeJS(arguments);
372+
DotNetDispatcher.EndInvokeJS(JSRuntime, arguments);
382373
});
383374
}
384375
catch (Exception ex)
@@ -416,7 +407,6 @@ public async Task DispatchEvent(string eventDescriptorJson, string eventArgsJson
416407
{
417408
await Renderer.Dispatcher.InvokeAsync(() =>
418409
{
419-
SetCurrentJSRuntime();
420410
return Renderer.DispatchEventAsync(
421411
webEventData.EventHandlerId,
422412
webEventData.EventFieldInfo,
@@ -444,7 +434,6 @@ public async Task OnLocationChangedAsync(string uri, bool intercepted)
444434
{
445435
await Renderer.Dispatcher.InvokeAsync(() =>
446436
{
447-
SetCurrentJSRuntime();
448437
Log.LocationChange(_logger, uri, CircuitId);
449438
var navigationManager = (RemoteNavigationManager)Services.GetRequiredService<NavigationManager>();
450439
navigationManager.NotifyLocationChanged(uri, intercepted);

src/Components/Server/src/Circuits/RemoteJSRuntime.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ public RemoteJSRuntime(IOptions<CircuitOptions> options, ILogger<RemoteJSRuntime
2222
_options = options.Value;
2323
_logger = logger;
2424
DefaultAsyncTimeout = _options.JSInteropDefaultCallTimeout;
25+
JsonSerializerOptions.Converters.Add(new ElementReferenceJsonConverter());
2526
}
2627

2728
internal void Initialize(CircuitClientProxy clientProxy)
@@ -58,7 +59,7 @@ private void EndInvokeDotNetCore(string callId, bool success, object resultOrErr
5859
{
5960
_clientProxy.SendAsync(
6061
"JS.EndInvokeDotNet",
61-
JsonSerializer.Serialize(new[] { callId, success, resultOrError }, JsonSerializerOptionsProvider.Options));
62+
JsonSerializer.Serialize(new[] { callId, success, resultOrError }, JsonSerializerOptions));
6263
}
6364

6465
protected override void BeginInvokeJS(long asyncHandle, string identifier, string argsJson)

src/Components/Server/src/Microsoft.AspNetCore.Components.Server.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
<ItemGroup>
4242
<Compile Include="$(ComponentsSharedSourceRoot)src\CacheHeaderSettings.cs" Link="Shared\CacheHeaderSettings.cs" />
4343
<Compile Include="$(ComponentsSharedSourceRoot)src\ArrayBuilder.cs" LinkBase="Circuits" />
44+
<Compile Include="$(ComponentsSharedSourceRoot)src\ElementReferenceJsonConverter.cs" />
4445

4546
<Compile Include="..\..\Shared\src\BrowserNavigationManagerInterop.cs" />
4647
<Compile Include="..\..\Shared\src\JsonSerializerOptionsProvider.cs" />

0 commit comments

Comments
 (0)