Using IDbContextFactory and DbContext In The Same #AspNetCore app

preview_player
Показать описание
Sometimes we need to work with both the regular DbContext and with IDbContextFactory at the same Asp.Net Core app. Here are two popular use cases:

1️⃣ Blazor Server, when we need to have both components and controllers and Razor Pages in the same project
2️⃣ When running background jobs, like Hangfire.

❗❗❗❗There's however a nasty exception just around the corner. If we try to run the application, we'll get an exception saying that a scoped service can't be consumed in a singleton service.

🤔So, what's wrong? Let me walk you through this.

Join this channel to get source code access and other perks:

Also follow me here (especially if you are a self taught developer):

Contents
1. Intro: 00:00
2. Do we even need this? 01:02
3. Throwing Blazor Server in the mix 03:52
4. Annoying exception: 05:13
5. C'mon. it's that simple?! 07:32
6. Conclusion: 09:37

My setup:
Рекомендации по теме
Комментарии
Автор

Aaahh.. I've justed wasted a few hours on this problem - just changed the order as you proposed and it worked. Thank you very much!

GipfelstuermerDe
Автор

Great video and great advanced content. It helped me a lot. Please, keep them videos coming!!

chiellini
Автор

Amazing. Thanks you probably saved me a couple hours lmao

letsplay
Автор

Thankyou so much for posting this. The issue very rarely pops up in my Blazor Server + Identity project. So rare that it is difficult to debug and never a priority. Just annoying :-)

I had a transient scoped DbContext below IDbContextFactory. Hoping that using singleton solves it completely. Cheers

David-krfx
Автор

So the natural follow-up for me is how do I then mock that correctly when unit testing repository? There is surprisingly little online.

nevernerd
Автор

Great video. However, won't using per-operation dbcontext or a transiant DBContext take away all the benefits of using EF Core? Such as lazy-loading, Change Tracking, First-Level Cache, Unit of Work... At that point EF Core just becomes an ORM. And since scoped DBContext doesn't work well with Server-side Blazor at all, it requires implementing something custom, with some kind of Context Locator that allows to use one DBContext per business operation/transaction.

AmortizedLogN
Автор

Hello, I like your videos, you have very good content!
I would like to see a video for multi-tenants in minimal api.

DanyAracena
Автор

Good information but background music is distracting

guyonfellow
Автор

"Singleton" DbContext. huh. Exactly wrong. Video nice but last minute.

NuriYilmaz