.NET 7 - Minimal Api and DI
.NET 7 - Minimal Api and DI

.NET 7 – Minimal API and Dependency Injection

In previous article, we have discussed about how the Serilog file sink can be configured in minimal API project. In this article, we are going to have a look at configuring dependency injection in the same project.

Dependency injection is bit tricky with minimal API. With an ASP .NET Core Web API which uses controllers, it is very easy to understand as controllers have the constructors and dependencies are resolved via their constructors. But, in case of minimal APIs, there would mostly be not be a constructors involved. Hence, the dependency resolution part is bit different.

In the following sections, we will first have a look at how to register the dependencies and then, we will see how the dependencies can be resolved.

Registering Dependencies

Registering dependencies in minimal API project is exactly similar to what we need to do in API project with controllers. For the sake of this discussion, I have used the default DI container that comes with ASP .NET Core Web API apps. It has methods – AddTransient, AddScoped and AddSingleton – to register the dependencies.

Let’s take the example of our file StudentsApi.cs that we have created in previous article. In this file, we have directly injected UniversityDbContext in the API handlers. We could do that because we have registered the DbContext dependency by calling AddDbContext API in AppBuilder.

Let’s say, instead of directly injecting DbContext in API handlers, we want to create a StudentsRepository. So, let’s go to MinimalApiDemo.DataAccess and create the repository. The repository should look somewhat similar to code snippet given below.

Now, it’s time to register this dependency. Let’s move to AppBuilder class. We can register the dependency, IStudentRepository, by calling builder.Services.AddTransient – as shown in the code snippet given below.

Resolving Dependencies

Now, let’s open StudentsApi.cs. If you have followed previous article about Minimal Api with EF Core, you already know that we have injected UniversityDbContext in the API handlers.

So, now instead of injecting the UniversityDbContext, let’s inject the IStudentRepository in the handlers. The full code snippet is given below.

Wrapping Up

So, as you can see, registering the dependencies is same as in any other .NET Core Web API project. Resolving dependency is bit different in case of minimal APIs. Instead of injecting dependencies in the constructor, the dependencies are injected in handler methods.

I hope you find this information helpful. Let me know your thoughts.

Leave a Reply Cancel reply