How to Use EF Dependency Injection with Called Method

Kmcnet 691 Reputation points
2022-08-25T00:59:14.28+00:00

Hello everyone and thanks for the help in advance. Attempting to learn dependency injection concepts with C# and MVC controller. I am reading through the article https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/. My question is, let's assume within my MVC controller, an async method is called requiring the context object. Should you instantiate the context in the controller, then pass it to the method that consumes it, or do I instantiate it within the method. My controller may need to make more than one method call where each method requires the context. How should this be handled?

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
697 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,158 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Farid Uddin Kiron MSFT 456 Reputation points Microsoft Vendor
    2022-08-25T02:41:51.667+00:00

    Hi @Kmcnet Thanks for sharing your concern with us. Regarding your question tough our official document clear instruction for your scenario however, I am trying to explain it as per your scenario.

    In genral ApplicationDbContext can be used in ASP.NET Core controllers or other services through constructor injection Like below:

    public class HomeController  
    {  
        private readonly ApplicationDbContext _context;  
      
        public HomeController(ApplicationDbContext context)  
        {  
            _context = context;  
        }  
    }  
    

    Note: Once you initiate the _context globally then it can be used in Controller Action level. Now let's consider your below scenario:

    Question: My controller may need to make more than one method call where each method requires the context. How should this be handled?

    As you might know Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance. In that case, if you only need to call the method one after another then async, await can resolve your issue. However, if you want to call them concurrently then this way won't work for you and it will throw InvalidOperationException

    Handle Parallel Method Operation:

    Using dependency injection, this can be achieved by either registering the context as scoped, and creating scopes (using IServiceScopeFactory) for each thread, or by registering the DbContext. For example

    public class EFDenpendencyHostedService : IHostedService  
    {  
        private readonly IServiceScopeFactory scopeFactory;  
      
        public EFDenpendencyHostedService(IServiceScopeFactory scopeFactory)  
        {  
            this.scopeFactory = scopeFactory;  
        }  
      
        public void ExecuteDbContext()  
        {  
            using (var scope = scopeFactory.CreateScope())  
            {  
                var dbContext = scope.ServiceProvider.GetRequiredService<YourDbContext>();  
                …  
            }  
        }  
        …  
    }   
    

    Note: Once you have created the middleware hosted service then register it in the startup.cs/ program.cs class

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,
    Md Farid Uddin Kiron