By default, when you call AddDbContext
, you register a scoped DbContext
instance. This means that anywhere within the handling of a single request, requesting said DbContext
via DI will give you the same instance. With the double registration you have, the DI system will give you a different instance depending upon whether you ask for an IMyDbContext
or a MyDbContext
.
To instruct the DI system to give you the same instance for both types, use the following approach:
services.AddDbContext<MyDbContext>();
services.AddScoped<IMyDbContext>(sp => sp.GetRequiredService<MyDbContext>());
The first call registers MyDbContext
and the second simply forwards requests for IMyDbContext
to that same scoped MyDbContext
instance.