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

asp.net-core c# entity-framework-6

Question

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
1
0
2/5/2020 5:03:06 AM

Accepted Answer

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, its initialising withoutthe connection string as that is plumbed up when its 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.

0
2/5/2020 4:54:02 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow