Fix the ‘Unable to resolve service for type Microsoft EntityFrameworkCore DbContext’ error after scaffolding an MVC Controller in Visual Studio

If you’ve got this error after scaffolding a controller which uses Entity Framework Core like below…

Scaffold a new controller in Visual Studio

it means you haven’t registered your DbContext as a service. You need to do this as the scaffolded controller uses dependency injection to inject an instance of your DbContext into its constructor. For example here is a sample scaffolded controller…

Dependency Injection in controller

MVC is throwing the exception as it cannot find what class implements EFContext when it is attempting to create an instance of the CustomersController class.

To fix this we can amend the scaffolded controllers to create a DbContext instance directly in their constructors but the better way is to simply register the EFContext as a service in the Startup.cs -> ConfigureServices method. We can do this by calling the AddDbContext method as shown below…

Register DbContext

The code above will register EFContext as a scoped service which means it is tied to the request which is ideal in a web application. As you can see we can also configure options such as which provider we are using… but we don’t have to do this here, we can defer this to the OnConfiguring method in our DbContext class if we wish.

2 thoughts on “Fix the ‘Unable to resolve service for type Microsoft EntityFrameworkCore DbContext’ error after scaffolding an MVC Controller in Visual Studio”

Leave a Reply

Your email address will not be published. Required fields are marked *