Home > Back-end >  How to extend service collection of application project to web api in ASP.NET Core 6?
How to extend service collection of application project to web api in ASP.NET Core 6?

Time:06-10

I create new ASP.NET Core 6 solution for a Web API with onion architecture, I just found it, in .NET 6, there is change about dependency injection.

This is my solution structure:

Solution
|- Application
|- Domain
|- Infrastructure
|- API

In Application project, I create this code for dependency injection:

namespace Application
{
    public static class DependencyInjection
    {
        public static void AddApplication(this IServiceCollection services)
        {
            services.AddMediatR(Assembly.GetExecutingAssembly());
        }
    }
}

After that I added Application project as dependency in application.

In previous versions of .NET Core, I can add this to Startup.cs like this services.AddApplication();, but in new .NET 6, I can not find Startup.cs and when I google it, .NET 6 has a different way to use dependency injection.

I already try add code in Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddApplication();  <--- this one

builder.Services.AddControllers();

but it got error

IServiceCollection does not contain AddApplication()

Please help me how to add dependency collection in .NET 6 properly.

CodePudding user response:

Add Application as project reference to your Api project and it should resolve itself. And in using statements add using Application;

  • Related