© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•10mo ago•
28 replies
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");
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?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ how to use swagger in console application?
C#CC# / help
3y ago
How to configure services in my cli application:
C#CC# / help
13mo ago
attach console to a non console application?
C#CC# / help
2y ago
✅ How to get Options from DI
C#CC# / help
2y ago