jasontaylordev / NorthwindTraders

Northwind Traders is a sample application built using ASP.NET Core and Entity Framework Core.
MIT License
5k stars 1.59k forks source link

Question: Initialise NorthwindDbContext with DI (second ctor) #195

Closed morgrowe closed 5 years ago

morgrowe commented 5 years ago

In Northwind.Persistence.NorthwindDbContext.cs, we've implemented a constructor that takes one argument (options) and a second that takes 3, (options, currentUserService and dateTime). How/where do I initialise the NorthwindDbContext so that the currentUserService and dateTime dependencies are available?

The reason I ask is because one of the entities I'm trying to seed is an AuditableEntity, and when I do x.SaveChangesAsync(ct), it throws a null reference exception. After tracking it down, it's because the _currentUserService is null (and I assume _dateTIme is too).

I'm pretty new to all this, so apologies if this is dull question.

Keep up the great work!

Cheers, Morgan

morgrowe commented 5 years ago

Turns out I missed a line when recreating this file when moving these ideas to my own project:

https://github.com/JasonGT/NorthwindTraders/blob/master/Src/Persistence/DependencyInjection.cs

I didn't have this line:

services.AddScoped<INorthwindDbContext>(provider => provider.GetService<NorthwindDbContext>());

After adding it, it worked. Silly me.