如何在 asp.net 核心 2 中的静态 method/class 中访问数据库上下文

how to access db context within a static method/class in asp.net core 2

我有一个带有 EF 6 的 asp.net 核心 2 web 应用程序。到目前为止,我使用数据库上下文的方式是使用 asp.net 核心提供的依赖注入将上下文注入控制器:

protected DbContext dbContext;

public BaseController(DbContext context)
{
    dbContext = context;
}

在我的许多 razor 视图中,我调用扩展方法来初始化 telerik 网格,并向其传递选项。到目前为止,我还不需要访问数据库上下文,但现在我需要在扩展方法中访问它以实现某些逻辑:

    public static GridBuilder<T> BaseProcessGrid<T>(this GridBuilder<T> helper, string controllerName, string gridName)
       where T : class, IProcessViewModel
    {
        bool showDelete = false;

        //check if the current user has edit rights 
        using (var db = new DbContext())
        {
            var users = db.Users.ToList(); // <--- this just doesn't get any records.
        }

当试图从静态方法中实例化一个新的数据库上下文时,它只是不获取任何记录。我需要弄清楚如何实际访问 DbContext 的新实例,或者以某种方式访问​​我的 Startup.cs:

中定义的作用域服务
services.AddScoped(_ => new MantleMapperContext(Configuration.GetConnectionString("DbContext")));

编辑:

按照下面的建议,我最终将 dbContext 服务直接注入到我的视图中,然后将其传递到方法中,如下所示:

@inject DbContext dbContext

您将必须传入您的 DbContext,或从 容器 中获取一个 实例,您将在其中- turn 也需要一个静态引用(这会使大多数代码审查失败)。

做你正在做的事情,它是在没有 连接字符串 的情况下进行初始化的,因为它是在注入时检测到的。

因为这是 static,最简洁的解决方案是传入 DbContext

public static GridBuilder<T> BaseProcessGrid<T>(this GridBuilder<T> helper, DbContext db, string controllerName, string gridName)
   where T : class, IProcessViewModel
{
    bool showDelete = false;

    var users = db.Users.ToList(); // <--- gets records.

更新

how would i do that from within the razor view?

我相信你可以将服务注入视图。

Service injection

A service can be injected into a view using the @inject directive. You can think of @inject as adding a property to the view, and populating the property using DI.