.NET 6 - Inject service into program.cs

Viewed 8560

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?

4 Answers

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<SomeService>();

someService.DoSomething();

You add your service to the builder.Services collection and then access it with

var myService = services.BuildServiceProvider().GetService<MyService>();

Inside the program.cs file you can manage your services by builder.Services

For example, I added DbContext and Two different services based on the Singleton pattern and Scoped

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddDbContext<MyDbContext>(options =>
{
    // options.UseSqlServer(...);
});
builder.Services.AddSingleton<IMyService, MyService>();
builder.Services.AddScoped<IMySessionBasedService, MySessionBasedService>();

For more information check Code samples migrated to the new minimal hosting model in ASP.NET Core 6.0

I tried to use the GetService method but I pass the service interface type as input (as shown below) and this worked with me.

var app = builder.Build();    
var injectedService1 = app.Services.GetService<IToInjectService>();
injectedService1.DoSomething();
Related