Reputation: 329
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.
Upvotes: 4
Views: 3424
Reputation: 329
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.
Upvotes: 3