【发布时间】:2021-07-11 19:45:27
【问题描述】:
我希望在我的 Blazor 应用程序中创建一个全局类,该类包含一个函数,该函数通过我从 Windows 身份验证获得的用户用户名获取用户的部门,但我似乎无法通过我的全局访问 HttpContextAccessor班级。当我注入它时,它就像它可以访问HttpContext,但是当它运行时,我得到了错误
System.NullReferenceException: '对象引用未设置为对象的实例。'
当你在局部变量中查看访问器时,访问器为空。
我进行了很多谷歌搜索,但找不到任何与我正在做的事情以及我目前对这些事情如何运作的了解很好地融合在一起的东西。
这是我的全局类:
public class Global
{
[Inject]
IHttpContextAccessor HttpContextAccessor { get; set; }
public string Identity;
public string Department;
public Global()
{
Identity = HttpContextAccessor.HttpContext.User.Identity.Name;
CalculateDepartment(Identity)
}
private void CalculateDepartment (string identity) {
//Calculate what department the person is in based on user ID
Department = CalculatedDepartment;
}
}
这是我的启动:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor(o => o.DetailedErrors = true);
services.AddTelerikBlazor();
services.AddHttpContextAccessor();
services.AddSingleton<Global>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.ApplicationServices.GetRequiredService<Global>();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
Google 说要使用 services.AddScoped<Global>,但我发现这不适用于我的 CalculateDepartment 函数,当我使用 services.AddSingleton<Global> 时它起作用了,所以我一直这样。
它似乎对我尝试以这种方式注入此文件的任何内容执行此操作。我可以将东西注入任何其他页面,但显然不能注入此类。有几个人只是说将它注入构造函数,但这对我没有多大帮助,因为我对此很陌生,而且我无法让我发现的例子起作用。不过,这可能是解决方案,也许我只需要以一种可行的方式来做。也可能有更好的方法来创建一个全局类。
【问题讨论】:
标签: dependency-injection singleton global-variables blazor httpcontext