When using Entity Framework Core and ASP.NET Core MVC we can easily inject a DbContext instance into our controller, repository or service classes as Dependency Injection is built into .NET Core.
The image below (click for a larger view in a new window) shows the steps involved…
– Step 1 –
Register the DbContext as a service in the ConfigureServices method in the Startup.cs file. AddDbContext creates a Scoped service, this means it is tied to the request, which is ideal in a web app.
– Step 2 –
Inject into and use the service in your consuming class or classes. Many ways to do this but I’ve shown two below. In 2a we inject the specific service and in 2b we inject an instance of IServiceProvider which can be useful if we have many services required in addition to a DbContext.
I recommend injecting the specific service as this expresses intent more clearly and makes it more obvious to other developers what the dependencies are. Indeed the IServiceProvider approach is an example of the service locator pattern which many consider to be an anti pattern but make your own mind up… every pattern can be turned into an anti pattern if its used unwisely.
Do I inject DbContext into controller, service or repository classes?
Note… in the example above I’ve injected directly into the controller class. I’m just doing this to keep things simple for the purposes of this post. In real apps I wouldn’t recommend this as it means your EF logic resides in your MVC controller action methods meaning you couldn’t re-use it in another web app, console app etc.
Whether or not to use the repository pattern with Entity Framework and therefore inject the DbContext into repository rather than service classes is a whole different question. I don’t use it in most EF apps but this topic has been debated online for years and everyone has a different opinion on it so please do your own research here.