[英]how to access db context within a static method/class in asp.net core 2
I have an asp.net core 2 webapplication with EF 6. The way I have been using db context so far is using dependency injection provided by asp.net core to inject the context into controllers:我有一个带有 EF 6 的 asp.net core 2 webapplication。到目前为止,我一直使用 db context 的方式是使用 asp.net core 提供的依赖注入将上下文注入控制器:
protected DbContext dbContext;
public BaseController(DbContext context)
{
dbContext = context;
}
In many of my razor views, I call an extension method to initialize a telerik grid, passing it options.在我的许多 razor 视图中,我调用了一个扩展方法来初始化一个 Telerik 网格,并传递它的选项。 So far I have not needed to access the db context, but now I need to access it in the extension method for some logic:
到目前为止,我还不需要访问 db 上下文,但现在我需要在扩展方法中访问它以实现某些逻辑:
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.
}
When trying to instantiate a new db context from within the static method, it just doesn't fetch any records.当试图从静态方法中实例化一个新的数据库上下文时,它只是不获取任何记录。 I need to figure out how to actually access a new instance of the DbContext, or somehow access the scoped service defined in my Startup.cs:
我需要弄清楚如何实际访问 DbContext 的新实例,或者以某种方式访问在我的 Startup.cs 中定义的范围服务:
services.AddScoped(_ => new MantleMapperContext(Configuration.GetConnectionString("DbContext")));
EDIT:编辑:
As suggested below, I ended up injecting the dbContext service directly into my view and then passing it into the method like so:如下所示,我最终将 dbContext 服务直接注入到我的视图中,然后像这样将其传递到方法中:
@inject DbContext dbContext
You will have to pass in your DbContext
, or get an instance from the container which you will in-turn need a static reference too (this would fail most code reviews).您将必须传入您的
DbContext
,或者从容器中获取一个实例,您反过来也需要一个静态引用(这会使大多数代码审查失败)。
Doing what you are doing, it's initialising without the connection string as that is plumbed up when it's injected.做你正在做的事情,它在没有连接字符串的情况下进行初始化,因为它在注入时会被连接起来。
Since this is static
the neatest solution is to just pass in the DbContext
.由于这是
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.
Update更新
how would i do that from within the razor view?
我将如何从剃刀视图中做到这一点?
I believe you can inject services into views.我相信您可以将服务注入视图。
A service can be injected into a view using the @inject directive.
可以使用@inject 指令将服务注入到视图中。 You can think of @inject as adding a property to the view, and populating the property using DI.
您可以将@inject 视为向视图添加属性,并使用 DI 填充该属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.