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
" exception.
How to solve it…
You should pass all services that you will need in the constructor of the DbContext
-derived class and store them internally. Then you can use them in any of the infrastructure methods, such as OnConfiguring...