Server-side generic interop and support other namespaces
Hi, this looks very nice!
However, I wanted a generic implementation of sessionStorage that also supports server side Blazor. I thought I could easily generate that myself, as follows:
namespace MyApp;
[JSAutoGenericInterop(
TypeName = "Storage",
Implementation = "window.sessionStorage",
HostingModel = BlazorHostingModel.Server,
OnlyGeneratePureJS = true,
Url = "https://developer.mozilla.org/docs/Web/API/Window/sessionStorage",
GenericMethodDescriptors = [
"getItem",
"setItem:value"
])]
public partial interface ISessionStorageService;
That almost works, except for two things:
- The generated implementation, in
SessionStorageService.g.cs, doesn't contain ausing Microsoft.JSInterop;statement, so it doesn't work in another namespace. - The
FromJsonextension method doesn't work onValueTask<string>, so the currently generated code doesn't work. (Specifically in the implementation of GetItemAsync:
)ValueTask<TValue?> ISessionStorageService.GetItemAsync<TValue>(string key, JsonSerializerOptions? options) where TValue : default => _javaScript.InvokeAsync<string?>("window.sessionStorage.getItem", key).FromJson<TValue>(options);
As an additional note, I'd personally prefer if it wasn't required to add the FromJson and ToJson methods as extension methods to use the generic interop, as those methods now show up in the Intellisense of every object in my project (using Resharper).
Thanks for your help, and your work on this project!
Yeah, it's a bit limited right now. You could get this to work by setting the namespace of your interface to Microsoft.JSInterop:
namespace Microsoft.JSInterop;
[JSAutoGenericInterop(
TypeName = "Storage",
Implementation = "window.sessionStorage",
HostingModel = BlazorHostingModel.Server,
OnlyGeneratePureJS = true,
Url = "https://developer.mozilla.org/docs/Web/API/Window/sessionStorage",
GenericMethodDescriptors = [
"getItem",
"setItem:value"
])]
public partial interface ISessionStorageService;
As for the extension methods, yeah, that's a good callout. I'm still thinking on how to best address that.
Fixed in b2a509de6579457eaf14ce9cdd1286a62c768909