1

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>();

2 Answers 2

4

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)
    {
        // ...
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

How do I inject it in a static class? Static class should have a parameter-less constructor ?
You don't :) Use non-static classes and/or factories
1

you can inject the concrete type

public MyController(MyDb dbContext)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.