vany0114 / EF.DbContextFactory

With EF.DbContextFactory you can resolve easily your DbContext dependencies in a safe way injecting a factory instead of an instance itself, enabling you to work in multi-thread contexts with Entity Framework or just work safest with DbContext following the Microsoft recommendations about the DbContext lifetime.
http://elvanydev.com/EF-DbContextFactory/
MIT License
93 stars 21 forks source link

I am having doubts while learning DbContextFactory #32

Open shouhujishu opened 3 years ago

shouhujishu commented 3 years ago

Hello. I am having doubts when using DbContextFactory. Is there any difference between CreateDbContext() and new DbContext()? Is there any difference between using DbContextFactory and using(=new DbContext())? Thank you, can you tell me?

andreyeurope commented 3 years ago

@shouhujishu I don't know if you are still learning EF Core, but after spending a good amount of time, it seems there is really no best solution. If you create a new instance each time, sure, you might escape concurrency problems, but you lose other properties of EF Core, like Caching. And then if you want to span a DB transaction across multiple services, how do you do that? I am not an expert myself, but I would say you CAN'T. You'd have to pass around your original context and chose a point where you'd want to commit your transaction, or roll it back if you have any errors. Each approach has pros and cons, so you'd have to make the choice yourself. I don't think there's any bad approach (putting aside using the same DbContext within multiple threads).