Description
Preview 6 replaces DotNetObjectRef
with a generic DotNetObjectRef<T>
. Instead of a constructor, the Create<T>
method is now used.
When passing this
from within a component, this leads to unexpected results due to Razor's parsing behavior.
To Reproduce
Steps to reproduce the behavior:
- Using ASP.NET Core 3.0 Preview 6 and Visual Studio 2019 16.2 Preview 4
- Create a new Blazor component MySampleComponent.razor
- Place this code inside its
@code
section:
private DotNetObjectRef<MySampleComponent> _Instance;
protected override async Task OnAfterRenderAsync()
{
_Instance = DotNetObjectRef.Create(this);
}
- See error
Expected behavior
This should compile. The type parameter of Create<T>
should be inferred as MySampleComponent
.
Actual behavior
This doesn't work, because Razor internally renames your class to __generated__MySampleComponent
. Consequently, the Error List will show:
CS0029 Cannot implicitly convert type
Microsoft.JSInterop.DotNetObjectRef<__generated__MySampleComponent>
toMicrosoft.JSInterop.DotNetObjectRef<MySampleComponent>
If you explicitly specify the type parameter, the error changes to CS1503.
Workaround
You can declare the variable with the generated class name:
private DotNetObjectRef<__generated__MySampleComponent> _Instance;
protected override async Task OnAfterRenderAsync()
{
_Instance = DotNetObjectRef.Create(this);
}
However, this is presumably not the intended behavior.