Use injected service from JS code to static Blazor method

拜拜、爱过 提交于 2021-01-28 12:28:58

问题


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

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.

This all looks something like this:

My js code:

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

Blazor page:

@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...?
    }
}

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.

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?


回答1:


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);

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.



来源:https://stackoverflow.com/questions/58241562/use-injected-service-from-js-code-to-static-blazor-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!