eadam
eadam

Reputation: 26061

How to inject DbContext in MVC 6 using default dependency injection?

Can you please tell me how to inject a dbContext using the default dependency injection in MVC 6? Do I just need to create an interface and add it in the Startup.cs as below?

services.AddTransient<IMyDb, MyDb>();

Upvotes: 1

Views: 1097

Answers (2)

Bart Calixto
Bart Calixto

Reputation: 19705

you can inject the concrete type

public MyController(MyDb dbContext)

Upvotes: 1

Victor Hurdugaci
Victor Hurdugaci

Reputation: 28425

Yes, that should be enough. Then, as part of the controller parameters, add the interface and it will be injected:

class MyController
{
    public MyController(IMyDb dbContext)
    {
        // ...
    }
}

Upvotes: 4

Related Questions