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


Question [how to access db context within a static method/class in asp.net core 2] has 1 solution 2020-08-19 03:02:19 c#

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

Question [how to access db context within a static method/class in asp.net core 2] solution number 1

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.


.htaccess .net .net-core 2d 3d 3d-printing abp abstract-syntax-tree actions-on-google actionscript-3 active-directory activemq activemq-artemis acumatica adobe-xd aframe ag-grid agora.io air airflow ajax akka alert alexa algorithm alignment allure amadeus amazon-cloudformation amazon-cognito