【问题标题】:Null reference exception from object来自对象的空引用异常
【发布时间】:2023-03-26 00:37:01
【问题描述】:

我在 asp.net core 2.1 中有一个应用程序。我已经在 startup.cs 文件中注册/注入了 HttpContextAccessor,如下所示。

services.AddHttpContextAccessor();

我还为接口 IHttpContextAccessor 创建了一个对象,并在依赖注入类“GetScopedServicesTools”的构造函数中启动了该对象

 public readonly IHttpContextAccessor HttpContextAccessor;

 public GetScopedServicesTools(IHttpContextAccessor _httpContextAccessor)
 {
   HttpContextAccessor = _httpContextAccessor;
 }

我为 DI 类“GetScopedServicesTools”创建了一个对象,但不确定需要将什么值传递给该类的构造函数。

private GetScopedServicesTools getScopedServices;

您能否帮我将什么值传递给“GetScopedServicesTools”类的构造函数。

【问题讨论】:

    标签: c# asp.net-core asp.net-core-webapi nullreferenceexception


    【解决方案1】:

    如果您想将该类与 DI 容器一起使用,您还应该向服务提供者注册 GetScopedServicesTools

    在您的Startup.cs 中,您可以执行services.AddScoped<GetScopedServicesTools>();,然后只需将其注入您的控制器或您喜欢的任何地方。

    注意:

    然而,我想指出的是,DI 机制已经提供了开箱即用的功能,您可以通过 GetScopedServicesTools 类尝试实现这些功能。你可以简单地在任何你喜欢的地方注入 IHttpContextAccessor,因为你已经用services.AddHttpContextAccessor(); 向服务提供者注册了它。您对额外课程所做的事情是一种反模式,应该避免。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 2018-06-07
      • 2015-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多