'.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 1:[1]
You add your service to the builder.Services collection and then access it with
var myService = services.BuildServiceProvider().GetService<MyService>();
Solution 2:[2]
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
Solution 3:[3]
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();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wim Ombelets |
| Solution 2 | Mohi |
| Solution 3 | Edu_LG |
