Home > database >  .NET 6 - Inject service into program.cs
.NET 6 - Inject service into program.cs

Time:04-15

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?

CodePudding user response:

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

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

CodePudding user response:

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

  • Related