[英]How to use blazor scoped service in a class
I am trying to use a scoped service for AuthenticationStateProvider to get user details in different classes of the solution.我正在尝试使用 AuthenticationStateProvider 的范围服务来获取解决方案的不同类中的用户详细信息。 The service class that is used as scoped service looks like this:
用作范围服务的服务 class 如下所示:
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:我在启动时将 class 注册为范围服务,如下所示:
services.AddScoped<ServiceClass>();
Then trying to consume the service in another class DAL like this然后尝试像这样在另一个 class DAL 中使用该服务
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?但是在 saveBankCash 方法中,userClass 是 null,有人可以指导我这里有什么问题吗?
You will need to add a constructor to DAL like this:您需要像这样向 DAL 添加一个构造函数:
public DAL(ServiceClass s)
{
userClass = s;
}
Note that this will only work if you add DAL to the DI as well, like this:请注意,这仅在您将 DAL 添加到 DI 时才有效,如下所示:
services.AddScoped<DAL>();
The DI will then inject the dependencies in the call to the constructor.然后,DI 将在对构造函数的调用中注入依赖项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.