Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve DBContext with implements another interface in Asp.Net Core

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?

like image 973
Jedi31 Avatar asked Oct 24 '16 21:10

Jedi31


1 Answers

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.

like image 103
Tseng Avatar answered Oct 21 '22 17:10

Tseng