C#C
C#8mo ago
VoidPointer

✅ How to Get DI Services in a Console Application

After some reading of various sources, mainly the official MS docs, I have my console app set up like this and it all appears to be working fine:
var builder = Host.CreateApplicationBuilder(args);

builder.Configuration.Sources.Clear();
IHostEnvironment env = builder.Environment;
builder.Configuration
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true, true);

builder.Services.Configure<DbOptions>(builder.Configuration.GetSection("Database"));
builder.Services.AddTransient<EnvironmentService>();

using var serviceProvider = builder.Services.BuildServiceProvider();

var svc = serviceProvider.GetService<EnvironmentService>();
svc.ImportEnvironment(@"C:\Development\WorkProjects\Postman\Environments\seriti-V3-local-small.postman_environment.json");

My big question is how do I access a service provider to get a service in other classes in the app? Do I have to have a "root service" singleton that all the other services are injected into, then access that from everywhere else, or, as I hope, is the there a better way to get a service required for a task from other classes in the app?
Was this page helpful?