Recommended context factory injection method?
See original GitHub issueI’m looking to run some queries in parallel and understand that I’ll need to create multiple context instances for this. As such I’m looking to inject a factory rather that single instance. Would you be able to give a little guidance please as to a recommended approach?
It looks like runtime context factories aren’t something built-in, and the current DI helper:
…just registers the context type, of course.
Should I just implement my own IEfContextFactory<TContext>
type which depends on DbContextOptionsFactory<TContext>
? Is there a method you guys use for this scenario?
Issue Analytics
- State:
- Created 6 years ago
- Reactions:4
- Comments:17 (4 by maintainers)
Top Results From Across the Web
DbContext Lifetime, Configuration, and Initialization
Using dependency injection, this can be achieved by either registering the context as scoped, and creating scopes (using IServiceScopeFactory ) ...
Read more >Is there a way to factory inject a custom DbContext?
the subclass will dependency inject the specific dbcontext in its constructor and set the parent class dbcontext variable in its constructor.
Read more >How to Use Factory Pattern With Dependency Injection in . ...
We can inject a factory object that creates and provides instances of the dependencies instead of explicitly injecting the dependencies.
Read more >Best Practices in Using the DbContext in EF Core
This article talks about Db Context concepts and the best practices you can ... Don't use Dependency Injection for your DbContext Instances.
Read more >EF.DbContextFactory - El Vany dev
DbContextFactory you can resolve easily your DbContext dependencies in a safe way injecting a factory instead of an instance itself, enabling ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
You can try this.
When
scope
is disposed, it will automatically dispose all instances resolved from it.One important reason this would be necessary is for retryable transactions.
The current examples in the docs for ‘Connection Resiliency’ just create a new context as needed.
It is clearly necessary not to continue with the same context if you’re ‘adding’ items to a table, and then retrying the entire operation again if it fails - you’ll get duplicates.
That’s what led me here, and I’m using connection pooling so I thought perhaps there ought to be a well defined way to reset a context - especially since I know that functionality exists as that’s how connection pools work!