Last active
August 25, 2023 08:48
-
-
Save profiiqus/1baec8ece7743b680e925626dc103a37 to your computer and use it in GitHub Desktop.
C# Application startup builder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"Logging": { | |
"LogLevel": { | |
"Default": "Debug", | |
"Microsoft": "Warning", | |
"Microsoft.Hosting.Lifetime": "Information" | |
} | |
}, | |
"Serilog": { | |
"PathFormat": "Logs/log-{Date}.txt", | |
"LogLevel": { | |
"Default": "Debug", | |
"Microsoft": "Information" | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.Logging; | |
namespace Main; | |
/// <summary> | |
/// Service builder class. | |
/// </summary> | |
public static class ServiceBuilder | |
{ | |
/// <summary> | |
/// Builds the application services, including configuration and logging. | |
/// </summary> | |
/// <returns>Service provider with system services</returns> | |
public static ServiceProvider BuildServices() | |
{ | |
// Build configuration | |
var configurationBuilder = new ConfigurationBuilder() | |
.SetBasePath(Path.Combine(AppContext.BaseDirectory)) | |
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); | |
var configuration = configurationBuilder.Build(); | |
// Build service collection | |
var serviceCollection = new ServiceCollection() | |
.AddSingleton<IConfiguration>(configuration); | |
// Build logging | |
serviceCollection.AddLogging(loggingBuilder => | |
{ | |
loggingBuilder.ClearProviders(); | |
loggingBuilder.AddConfiguration(configuration.GetSection("Logging")); | |
loggingBuilder.AddConsole(); | |
loggingBuilder.AddFile(configuration.GetSection("Serilog")); | |
}); | |
// Register services from other libraries (optional) | |
DependencyHelper.RegisterServices(serviceCollection, configuration); | |
// Return built service provider | |
return serviceCollection.BuildServiceProvider(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment