使用 JSInterop/Blazor 的静态方法调用

Static method invocation using JSInterop/Blazor

(#)第一篇文章

我正在使用 JSInterop 和 Blazor/RazorPages 在单击 table 上的项目时调用一个方法。 Interop 规范只允许使用静态方法。好吧,从技术上讲,实例方法也可以使用,但相关文档确实令人困惑。我几乎可以肯定,如果没有 Blazor '@onclick' 标记助手,实例方法调用将无法工作——我无法在此示例中使用它。

这是有效的方法:

public class Dashboard : PageModel

private readonly DeviceService _deviceService;
public Dashboard (DeviceService deviceService)
{
     _deviceService = deviceService;
}

//I want to use the above instance of deviceService, for a JSInvokable method

[JSInvokable]
public static async Task<List<string>> DeviceDetails(string deviceName)
{
    List < string > details = new List<string>();
    Uri location = new Uri("http://superapi.com/api/devices");
    HttpClient client = new HttpClient();
    client.BaseAddress = location;

    DeviceService dev = new DeviceService(client);

    Device details = await dev.GetDeviceByName(deviceName);

    return details;
}
//This <script> is what the client gets in their browser when they visit the page.
function () {
            var table = $('#<TableName>').DataTable();
            var d = table.row(this).data();
            DotNet.invokeMethodAsync("<namespace>", "DeviceDetails", d[0])
                .then(data => {
                    document.getElementById("Property1").innerHTML = data[0];
                    document.getElementById("Property2").innerHTML = data[1];
                    document.getElementById("Property3").innerHTML = data[2];
                    document.getElementById("Property4").innerHTML = data[3];
                    document.getElementById("Property5").innerHTML = data[4];
                });
        });

invokeMethodAsync 的 MS 文档声明它仅适用于静态方法,不允许我访问我在 PageModel 中声明的 DeviceService 实例。它迫使我用 'new' 一切创建一个相当丑陋的新实例。

我认为解决方案可能涉及使用接口或依赖注入,有人有什么建议吗?

我通过研究依赖注入找到了这个问题的答案。我从 appsetting.json 中注册了一个字符串,使用:

IConfigurationSection baseAPI = Configuration.GetSection("BaseAddress");
services.Configure<ApiBaseAddress>(baseAPI);

然后在我注入的页面上:

@inject IOptions<ApiBaseAddress> BaseAddress

现在我们可以将这个 BaseAddress 发送到参数中的静态方法:

DotNet.invokeMethodAsync("<namespace>", "DeviceDetails", d[0], "@BaseAddress.Value.Uri")

这允许我们在 URI 创建期间访问:

Uri location = new Uri(baseUri + "/api/worker");

虽然这并不完美 - 我真的不想从头开始创建服务,但至少我不需要在部署期间更改多段代码。