简体   繁体   中英

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:

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. 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:

    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:

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:

@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).

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 .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM