使用从JS代码到静态Blazor方法的注入服务 [英] Use injected service from JS code to static Blazor method

查看:77
本文介绍了使用从JS代码到静态Blazor方法的注入服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用jQuery lib来显示确认"对话框的应用程序.

I have an app that uses a jQuery lib to show 'confirmation' dialogs.

当用户在对话框中单击确定"或取消"时,首先将对我的Javascript代码进行回调.从那里,我根据用户做出的决定调用Blazor方法.

When a user clicks 'OK' or 'Cancel' on the dialog, then first a callback is made to my Javascript code. From there I do a call to a Blazor method, based on the decision the user made.

这一切看起来像这样:

我的js代码:

$('.alert-yesno).on('click', function() {
    // For simplicity I immediately call the Blazor method
    DotNet.invokeMethodAsync('[Assembly name]', 'DoSomething')
                            .then(data => {
                                // do something...
                            });
});

blazor页面:

@inject MyService MyService

<button class="alert-yesno">Show dialog</button>

@code
{
    [JSInvokable]
    public static async Task DoSomething()
    {
        // How to use the non static MyService here...?
    }
}

一切正常.Javascript部分调用了我的Blazor方法.但是如何从那里使用 MyService ?这被注入到页面中.很好,因为它利用了依赖注入.

This all works fine. The Javascript part calls my Blazor method. But how can I use MyService from there? This is injected into the page. Which is good, because it makes use of dependency injection.

我不想每次都在 static 方法中创建一个 new 实例,因为那样的话,我会丢失所有自动注入的依赖项.

I don't want to create a new instance everytime from within the static method, because that way I loose all the auto injected dependencies.

我该如何解决这个问题?

How can I solve this issue?

推荐答案

请参见

See https://docs.microsoft.com/en-us/aspnet/core/blazor/javascript-interop?view=aspnetcore-3.0#instance-method-call for a more complete example, but you can pass a reference to the the .net instance to the javascript code by calling

DotNetObjectReference.Create(myInstance);

然后javascript代码可以在该对象上调用实例方法.由于组件(以及注入其中的服务)的寿命可能与jquery click处理程序不同,因此可能会导致其他问题,但是上面的链接应该是一个很好的起点.

Then the javascript code can call the instance method on that object. Since the component (and thus the service which is injected into it) has a potentially different lifespan than the jquery click handler, this might cause some other issues, but the link above should be a good starting point.

这篇关于使用从JS代码到静态Blazor方法的注入服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆