Accessing the service provider too soon

Do not access the internal service provider in OnConfiguring or OnModelCreating.

Problem

The Entity Framework Core context uses a service provider of its own, but it is possible to pass it an external service provider. Having a service provider to hand is appealing, because we can use it to pass any kind of services to the context.

The problem is that most likely, we will be making use of these services in one of the methods that are used to configure the DbContext, such as OnConfiguring or OnModelCreating, but, it turns out, if you try to access the underlying service provider, either the built-in or the passed instance, you will get an "An attempt was made to use the context while it is being configured

Get Entity Framework Core Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.