Search code examples
c#.netclassdependency-injectionstartup

.NET 6 - Inject service into program.cs


I know how to do dependency injection in the Startup.cs in .NET 5 (or before), but how do I do the same with the top-level Program.cs in .NET 6?

.NET 5: for example, I can inject a class in the Configure method

public class Startup
{
    public IConfiguration _configuration { get; }
    public IWebHostEnvironment _env { get; set; }

    public Startup(IConfiguration configuration, IWebHostEnvironment env)
    {
        _configuration = configuration;
        _env = env;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        // TODO
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IToInjectService serviceToInject)
    {
        // USE SERVICE
    }
}

How can I achieve this in .NET 6?


Solution

  • Using .Net 6 is easy. Just execute GetService method after configure app services and have ran Build method.

    WebApplication? app = builder.Build();
    
    var someService = app.Services.GetService<ISomeService>();
    
    someService.DoSomething();