Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use existing SignalR hubconnection in different pages in blazor

I have Blazor application (client and Server). In client application hub connection initialized in mainLayout with this code:

            _hubConnection = new HubConnectionBuilder().WithUrl(navigationManager.ToAbsoluteUri("/hub"), options =>
            {
                options.AccessTokenProvider = async () =>
                {
                    var accessTokenResult = await AccessTokenProvider.RequestAccessToken();
                    accessTokenResult.TryGetToken(out var accessToken);
                    return accessToken.Value;
                };
            }).Build();

This connection working fine in layout, but I don't understand how I get this connection to use on specific pages. I know how to get and use hubConnection in js, but not in blazor pages.

What I tried to do is to add a singleton to Main in program.css with this code :

        builder.Services.AddSingleton(sp =>
        {
            var navMan = sp.GetRequiredService<NavigationManager>();
            var accessTokenProvider = sp.GetRequiredService<IAccessTokenProvider>();
            return new HubConnectionBuilder()
                .WithUrl(navMan.ToAbsoluteUri("/hub"), options =>
                {
                    options.AccessTokenProvider = async () =>
                    {
                        var accessTokenResult = await accessTokenProvider.RequestAccessToken();
                        accessTokenResult.TryGetToken(out var accessToken);
                        return accessToken.Value;
                    };
                })
                .WithAutomaticReconnect()
                .Build();
        });

But it didn't work because I don't have access to IAccessTokenProvider, it seems reasonably but without it connection useless because any request will be failed due to lack of permission.

Establishing connection each time when I change page not seem to right from me.

Also, it not seems right to have multiple connection to one or couple hub, its seem to me like overkill and resource demanding.

like image 890
Igor Markiv Avatar asked Oct 23 '25 07:10

Igor Markiv


1 Answers

It was a mistake to use Singleton. Instead of singleton I added hubConnection as scoped like this :

        builder.Services.AddScoped(sp =>
        {
            var navMan = sp.GetRequiredService<NavigationManager>();
            var accessTokenProvider = sp.GetRequiredService<IAccessTokenProvider>();
            return new HubConnectionBuilder()
                .WithUrl(navMan.ToAbsoluteUri("/hub"), options =>
                {
                    options.AccessTokenProvider = async () =>
                    {
                        var accessTokenResult = await accessTokenProvider.RequestAccessToken();
                        accessTokenResult.TryGetToken(out var accessToken);
                        return accessToken.Value;
                    };
                })
                .WithAutomaticReconnect()
                .Build();
        });

and now I starting connection ones in mainLayout like this :

    [Inject] HubConnection _hubConnection { get; set; }

    protected override async Task OnInitializedAsync() => await StartupTask();

    async Task StartupTask()
    {
        await _hubConnection.StartAsync();
    }

after that all injection on another pages get same connection.

like image 96
Igor Markiv Avatar answered Oct 24 '25 21:10

Igor Markiv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!