.NET Core service worker DI example (#951)

* Added example source code

* Fix namespace name

* Added example source code

* Fix namespace name

* Fix sln file

* Update Program.cs

* Updated IKubernetes DI registration
This commit is contained in:
Manuel Menegazzo
2022-08-03 07:15:52 +02:00
committed by GitHub
parent e7441f0a8e
commit 7d019b4ae3
7 changed files with 101 additions and 2 deletions

View File

@@ -0,0 +1,17 @@
using k8s;
using workerServiceDependencyInjection;
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
// Load kubernetes configuration
var kubernetesClientConfig = KubernetesClientConfiguration.BuildDefaultConfig();
// Register Kubernetes client interface as sigleton
services.AddSingleton<IKubernetes>(_ => new Kubernetes(kubernetesClientConfig));
services.AddHostedService<Worker>();
})
.Build();
await host.RunAsync();

View File

@@ -0,0 +1,40 @@
using k8s;
namespace workerServiceDependencyInjection
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> logger;
private readonly IKubernetes kubernetesClient;
/// <summary>
/// Inject in the constructor the IKubernetes interface.
/// </summary>
/// <param name="logger"></param>
/// <param name="kubernetesClient"></param>
public Worker(ILogger<Worker> logger, IKubernetes kubernetesClient)
{
this.logger = logger;
this.kubernetesClient = kubernetesClient;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
// Read the list of pods contained in default namespace
var podList = kubernetesClient.CoreV1.ListNamespacedPod("default");
// Print pods names
foreach (var pod in podList.Items)
{
Console.WriteLine(pod.Metadata.Name);
}
await Task.Delay(1000, stoppingToken);
}
}
}
}

View File

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

View File

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

View File

@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk.Worker">
<PropertyGroup>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
</ItemGroup>
</Project>