Resolve DBContext with implements another interface in Asp.Net Core

asp.net-core, c#, entity-framework-core

Solution

In your case using the factory method should work fine.

services.AddScoped<IDbContext>(provider => provider.GetService(typeof(MyContext)));

This way you will resolve a new instance of `MyDbContext` (on first call) or return the already instantiated instance of it during a request on conclusive calls.

Problem

I have an EF Context that has it's signature ``` public class MyContext : DbContext, IDbContext { } ``` When I add it to services, I use it ``` services.AddDbContext<MyContext>(op => { op.UseSqlServer(configuration.GetConnectionString("DefaultConnection")); }); ``` But it's causing problems when I'm injecting the IDbContext, like this ``` services.AddScoped(typeof(IDbContext), typeof(MyContext)); ``` Because it's duplicating my DbContext, and It should be only one per request. How can I resolve it?

Original source