.NET Core C# MVC DBContext 在 class 文件中为 Null

.NET Core C# MVC DBContext is Null in class file

我有一个解决方案,里面有几个 'projects'。一个是 MVC Web 应用程序,另一个是 class 库。

在我的 MVC Web 应用程序中 Startup.cs 我正在注册 DbContext:

public void ConfigureServices(IServiceCollection services)
{
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
     services.AddSession();
     services.AddHttpContextAccessor();
     services.AddMemoryCache();
     services.AddSingleton<Controllers.HomeController>();
     services.AddRouting(options => options.LowercaseUrls = true);

     services.AddDbContext<AffiliateDatabaseContext>();
}

我在 class 库中设置了上下文,所有设置都在 appsettings 中设置了连接字符串(有效):

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
     if (!optionsBuilder.IsConfigured)
     {
          IConfigurationRoot configuration = new ConfigurationBuilder().SetBasePath(AppDomain.CurrentDomain.BaseDirectory).AddJsonFile("appsettings.json").Build();
          optionsBuilder.UseSqlServer(configuration.GetConnectionString("CustomerBilling"));
     }
}

我正在尝试在我的 class 库中的 class 文件中使用 DBContext 来执行 DI:

private static AffiliateDatabaseContext affilContext;

public PromotionLogic(AffiliateDatabaseContext _affilContext)
{
      affilContext = _affilContext;
}
public static IEnumerable<AffPromotion> GetAllPromotions()
{
      return affilContext.AffPromotion.Include("Company").Include("PromotionType").Include("Audience").Include("PromotionSportLink").Include("AffPromotionImage").OrderBy(x => x.Priority).AsEnumerable();
}

但是 affilContext 似乎是 NULL,我不断收到以下错误:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

我做错了吗?我需要一个接口还是什么?它似乎在控制器中工作正常。

另一种方法是将 DBContext 作为参数传递给函数吗?

问题是您要分配给 instance 构造函数中的 static 字段。由于您从不调用构造函数,因此该字段保持 null。解决方案是使用实例字段(没有static)。

因此:

private static AffiliateDatabaseContext affilContext;

必须是:

private AffiliateDatabaseContext affilContext;

进行此更改后,任何使用 affilContextstatic 方法也需要更改为非静态方法(即删除 static) .

您可能想将变量保留为 static。一般来说,对于数据库上下文而言,这不是一个好主意。它们不是为长寿命设计的,也不是线程安全的。因此 static 数据库上下文不适合在 Web 应用程序中使用。