Search code examples
c#asp.net-coredependency-injectiondependencies.net-8.0

Add IoC in Program.cs file in .NET 8 from Dependency Container


This is my IoC method in Dependency Container

public class DependencyContainer
{
    public static void RegisterServices(IServiceCollection service)
    {
        #region Services Injection

        service.AddScoped<IUserService, UserService>();

        #endregion

        #region Repositories Injection

        service.AddScoped<IUserRepository, UserRepository>();

        #endregion
    }
}

Now I want to add it in Program .cs in web Layer . How can I do it in .NET 8?

in .NET 5 it was:

    public static void RegisterServices(IServiceCollection services)
 {
  DependencyContainer.RegisterServices(services);
  }

but in .NET 8 that we have not public method, how can I do it?

enter image description here


Solution

  • WebApplicationBuilder returned by the WebApplication.CreateBuilder exposes Services property of type IServiceCollection which is used exactly for the purpose of DI services registrations, so:

    DependencyContainer.RegisterServices(builder.Services);
    

    This is covered in the migration to 6.0 docs: