Reputation: 158
I am trying to use a scoped service for AuthenticationStateProvider to get user details in different classes of the solution. The service class that is used as scoped service looks like this :
public class ServiceClass
{
private readonly AuthenticationStateProvider _authenticationStateProvider;
public ServiceClass(AuthenticationStateProvider authenticationStateProvider)
{
_authenticationStateProvider = authenticationStateProvider;
}
public async Task<string> GetIdentity()
{
var authState = await _authenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
return user.Identity.Name;
}}
I registered the class in startup as scoped service like this :
services.AddScoped<ServiceClass>();
Then trying to consume the service in another class DAL like this
public class DAL
{
private readonly ServiceClass userClass;
public async Task<bool> saveBankCash(TransactionBankCashHeader master, List<TransactionBankCashDetail> lines, string Doctype)
{
string user = await userClass.GetIdentity();
}
}
But in the saveBankCash method, userClass is null, can someone please guide me what is wrong here?
Upvotes: 0
Views: 1946
Reputation: 1878
You will need to add a constructor to DAL like this:
public DAL(ServiceClass s)
{
userClass = s;
}
Note that this will only work if you add DAL to the DI as well, like this:
services.AddScoped<DAL>();
The DI will then inject the dependencies in the call to the constructor.
Upvotes: 1