I'm struggling to inject a service (AuthenticationStateProvider) in a class in Blazor server. If I do it in a razor component, it is pretty simple:
@inject AuthenticationStateProvider AuthenticationStateProvider
and then
private async Task LogUsername()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
ClientMachineName = $"{user.Identity.Name}";
}
else
{
ClientMachineName = "Unknown";
}
}
However I need to do this, i.e. retrieve the authenticated user machine name, in a class instead of a razor component.
I tried for instance:
[Inject]
AuthenticationStateProvider AuthenticationStateProvider { get; set; }
public async Task LogUsername()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
ClientMachineName = $"{user.Identity.Name}";
}
else
{
ClientMachineName = "Unknown";
}
}
But this does not seem to work.
Any help would be much appreciated.