Skip to content

Instantly share code, notes, and snippets.

@seesharprun
Last active November 8, 2024 03:40
Show Gist options
  • Save seesharprun/7b12dcd5a198cd52fbd55754dcc0b43b to your computer and use it in GitHub Desktop.
Save seesharprun/7b12dcd5a198cd52fbd55754dcc0b43b to your computer and use it in GitHub Desktop.
Simple console application (Generic Host)
{
"Messages": {
"Salutation": "Hello"
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="*" />
</ItemGroup>
</Project>
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Hosting.Internal;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Services.AddSingleton<IHostLifetime, ConsoleLifetime>();
builder.Services.AddScoped<IMessageService, MessageService>();
builder.Services.Configure<Messages>(builder.Configuration.GetSection(nameof(Messages)));
builder.Services.AddSingleton<string[]>((_) => args);
builder.Services.AddHostedService<ConsoleWorkerService>();
IHost host = builder.Build();
await host.RunAsync();
internal record Messages
{
required public string Salutation { get; init; } = "Hello";
}
internal interface IMessageService
{
string GetMessage();
}
internal class MessageService(
IOptions<Messages> messagesOptions,
string[] arguments
) : IMessageService
{
private readonly Messages messages = messagesOptions.Value;
public string GetMessage() => $"{messages.Salutation}, {arguments.FirstOrDefault() ?? "World"}!";
}
internal class ConsoleWorkerService(
IMessageService messageService,
ILogger<ConsoleWorkerService> logger,
IHostApplicationLifetime hostApplicationLifetime
) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
string message = messageService.GetMessage();
logger.LogInformation(message);
hostApplicationLifetime.StopApplication();
}
}
{
"profiles": {
"console": {
"commandName": "Project",
"environmentVariables": {
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment