3

Since EF Core can't handle parallel queries at the same time on the same context instance as documentation says, is there any common pattern that we can achieve this in .NET Core 6 using dependency injection?

Given the condition that I have no write and all of them are .AsNoTracking in this scope.

4
  • 2
    Yes, change your context wrapper to transient so that each injection is a new instance. Commented Sep 7, 2022 at 18:52
  • The MS recommended approach is a factory, see answer below. @DavidL, do you agree? Commented Sep 7, 2022 at 20:06
  • @daniherrera that is specifically referring to a context with dependencies. I personally have used many factories in apps and they work fine as well. It depends on what your containing class represents. If that class ONLY represents the lifetime of the context, you can make it transient and you don't need the factory. If you want your class to be scoped OR you need to make multiple calls from multiple methods within the same lifetime, a factory is preferable, even if you do not have additional context dependencies. In either case, the OP's question doesn't have sufficient details. Commented Sep 7, 2022 at 20:13
  • Something to think about: parallel queries are genetally inadvisable on databases, as they are IO bound so each query is just going to slow the other down. It only really works when querying separate tables, preferably on different filegroups located on different disks. Commented Sep 7, 2022 at 22:19

1 Answer 1

3

Quoting MS Documentation:

The recommended approach to create a new DbContext with dependencies is to use a factory.

builder
   .Services
   .AddDbContextFactory<ContactContext>(opt =>
       opt
       .UseSqlite($"Data Source={nameof(ContactContext.ContactsDb)}.db"));

You can get the factory on constructor via DI as usual:

    IDbContextFactory<ContactContext> DbFactory

And create as many contexts as you need, don't forgot to dispose contexts.

using var context = DbFactory.CreateDbContext();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.