Skip to content

Instantly share code, notes, and snippets.

@acg9
Created May 23, 2019 20:46
Show Gist options
  • Save acg9/241b77f55f13f38e491b4c1f47503c34 to your computer and use it in GitHub Desktop.
Save acg9/241b77f55f13f38e491b4c1f47503c34 to your computer and use it in GitHub Desktop.
using Microsoft.Extensions.Configuration.AzureAppConfiguration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp
{
class Settings
{
public string Name { get; set; }
}
class SettingsWrapper
{
private Settings settings;
public SettingsWrapper(IOptionsSnapshot<Settings> settings)
{
this.settings = settings.Value;
}
public string Name => settings.Name;
}
class Service : IHostedService
{
private IServiceProvider serviceProvider;
public Service(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
using (var scope = this.serviceProvider.CreateScope())
{
var serviceWrapper = scope.ServiceProvider.GetService<SettingsWrapper>();
Console.WriteLine(serviceWrapper.Name);
await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
}
}
}
public async Task StopAsync(CancellationToken cancellationToken)
{
}
}
class Program
{
private static async Task Main(string[] args)
{
var host = new HostBuilder()
.ConfigureAppConfiguration((hostContext, config) =>
{
config.AddAzureAppConfiguration(options =>
options.Connect("AzureAppConfigurationConnectionString")
.Watch("Name", TimeSpan.FromSeconds(5))
);
})
.ConfigureServices((hostContext, services) =>
{
services.Configure<Settings>(hostContext.Configuration);
services
.AddHostedService<Service>()
.AddTransient<SettingsWrapper>();
});
await host.RunConsoleAsync();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment