How to Access Database DBContext in the Middleware using Entity Framework

Access Database DBContext in the Middleware using Entity Framework

In this article, we will see how to DBContext in Middleware Entity Framework in ASP.NET Core.

Today in this article, we will cover below aspects,

As we know Middleware is a component that is used in the application pipeline to handle requests and responses which can also help perform pre and post-operation within the API pipeline.

We shall use the approach of the middleware component for handling DBContext within the ASP.NET Core API pipeline.

Getting Started

Let’s create an ASP.NET Core 3.1 or .NET 6 application.

Let’s create a very basic middleware component as below,

Create Middleware component

Let’s create a very basic middleware component as below,

public class CustomMiddleware
    {
        private readonly RequestDelegate _next;

        public CustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext httpContext)
        {
            try
            {
                await _next(httpContext);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Something went wrong: {ex.Message}");
            }
        }
    }

Above scaffolding, you get out of the box using Middleware Item templates available in Visual Studio-Right Click on Project-Add New Item and search with Middleware in item list as shown below,

Access Database DBContext in the Middleware using Entity Framework

So far above middleware component doesn’t use any DBContext object.

Let’s now add a DBContext object to the API pipeline using the AddDBContext extension method as below,

AddDbContext service extension method as above will make EmployeeContext available for the injection from the service container and will also manage to create a Scoped life instance of the given Context.

Lets now inject the DBContext class i.e EmployeeContext in the middleware as below,

DBContext Cannot resolve scoped service from root provider

Above our 2nd parameter to the InvokeAsync method is now EmployeeContext object.

Now this object can be used to perform any CRUD operation within that middleware component.

Middleware extension method

Use the below the extension method to present the middleware through IApplicationBuilder.

 public static class GlobalCutomMiddleware
    {
        public static void UseGlobalCustomMiddleware(this IApplicationBuilder app)
        {
            app.UseMiddleware<CustomMiddleware>();
        }
    }

Finally, use the below code to enable middleware using UseGloablCustomMiddleware() method in the API pipeline,

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseGlobalCustomMiddleware();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

If you use another way to inject the DBContext object, you may see the error “Cannot resolve scoped service from root provider”. But using the above middleware approach, you should be able to resolve the issue.

That’s All! Happy Coding!

Do you see any improvement to the above code? Do you have any suggestions or thoughts? Please sound off your comments below.

References :

Summary

Today In this article, we learned how to access the Database DBContext using the Middleware component in the ASP.NET Core pipeline. Middleware components play an important role in API pipeline and today we looked at possible usage of Database context in the Middleware component using Entity framework in API pipeline container.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



9 thoughts on “Use Database DBContext in Middleware Entity Framework Core

  1. Thank you very much for the Tip.

    I got this issue while adding a custom middleware which needs to access DBContext and got it resolved by the approach you provided.

  2. Thank you very much for this post.
    The error message “Cannot resolve scoped service from root provider” appeared for me when I tried to access the DbContext in the constructor of the middleware component. The key is to access it in the InvokeAsync function, as shown in the article. Keep it out of the constructor.

  3. Please sir, you didn’t provide The IEmployeeRepository implementation.

    Am getting an error Cannot resolve Scoped service from root provider
    Please help

      1. Thanks sir for your reply, Actually am not performing CRUD operation, I want to use middleware to get the total no of views on my page

        I.e if a user navigates to my page, example, Destrotech.com/C#

        let Page view in DB increment by 1, and possibly store the user in cookie, if he closes the tab and opens the page again, repeat the same thing..

        So I really don’t know how to implement this.. please help me sir

Leave a Reply

Your email address will not be published. Required fields are marked *