Skip to content

Commit

Permalink
additional explanations in the examples, simplified some code, tidied…
Browse files Browse the repository at this point in the history
… up, and replaced .ReadLine() with .ReadKey() (Since we want to exit with ANY key). (#243)

Enhancements for .NET Core 2 examples
  • Loading branch information
SheepReaper authored and 304NotModified committed Sep 17, 2018
1 parent b3f2fe8 commit d312930
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 45 deletions.
39 changes: 22 additions & 17 deletions examples/NetCore2/ConsoleExample/Program.cs
Original file line number Diff line number Diff line change
@@ -1,63 +1,68 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Extensions.Logging;
using System;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;

namespace ConsoleExample
{
class Program
internal class Program
{
static void Main(string[] args)
private static void Main()
{
var logger = NLog.LogManager.GetCurrentClassLogger();
var logger = LogManager.GetCurrentClassLogger();
try
{
var servicesProvider = BuildDi();
using (servicesProvider as IDisposable)
var servicesProvider = BuildDi();
using (servicesProvider as IDisposable)
{
var runner = servicesProvider.GetRequiredService<Runner>();
runner.DoAction("Action1");

Console.WriteLine("Press ANY key to exit");
Console.ReadLine();
Console.ReadKey();
}
}
catch (Exception ex)
{
//NLog: catch setup errors
// NLog: catch any exception and log it.
logger.Error(ex, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
LogManager.Shutdown();
}
}


private static IServiceProvider BuildDi()
{
var services = new ServiceCollection();

//Runner is the custom class
// Runner is the custom class
services.AddTransient<Runner>();

services.AddSingleton<ILoggerFactory, LoggerFactory>();
services.AddSingleton(typeof(ILogger<>), typeof(Logger<>));
services.AddLogging((builder) => builder.SetMinimumLevel(LogLevel.Trace));
services.AddLogging(builder => builder.SetMinimumLevel(LogLevel.Trace));

var serviceProvider = services.BuildServiceProvider();

var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();

//configure NLog
loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true });
// configure NLog
loggerFactory.AddNLog(new NLogProviderOptions
{
CaptureMessageTemplates = true,
CaptureMessageProperties = true
});

return serviceProvider;
}
}


public class Runner
{
private readonly ILogger<Runner> _logger;
Expand All @@ -72,4 +77,4 @@ public void DoAction(string name)
_logger.LogDebug(20, "Doing hard work! {Action}", name);
}
}
}
}
57 changes: 29 additions & 28 deletions examples/NetCore2/HostingExample/Program.cs
Original file line number Diff line number Diff line change
@@ -1,62 +1,63 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace HostingExample
{
public class Program
{
static async Task Main(string[] args)
private static async Task Main()
{
var logger = NLog.LogManager.GetCurrentClassLogger();
var logger = LogManager.GetCurrentClassLogger();
try
{
var hostBuilder = new HostBuilder().UseNLog().ConfigureServices((hostContext, services) =>
{
services.AddScoped<IHostedService, ConsoleHostedService>();
});
var hostBuilder = new HostBuilder()
.UseNLog()
.ConfigureServices((hostContext, services) => services.AddHostedService<ConsoleHostedService>());

// Build and run the host in one go; .RCA is specialized for running it in a console.
// It registers SIGTERM(Ctrl-C) to the CancellationTokenSource that's shared with all services in the container.
await hostBuilder.RunConsoleAsync();
Console.WriteLine("Press ANY key to exit");
Console.ReadLine();

Console.WriteLine("The host container has terminated. Press ANY key to exit the console.");
Console.ReadKey();
}
catch (Exception ex)
{
//NLog: catch setup errors
logger.Error(ex, "Stopped program because of exception");
// NLog: catch setup errors (exceptions thrown inside of any containers may not necessarily be caught)
logger.Fatal(ex, "Stopped program because of exception");
throw;
}
finally
{
// Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
NLog.LogManager.Shutdown();
LogManager.Shutdown();
}
}

public class ConsoleHostedService : Microsoft.Extensions.Hosting.IHostedService
public class ConsoleHostedService : BackgroundService
{
readonly ILogger<ConsoleHostedService> _logger;
private readonly ILogger<ConsoleHostedService> _logger;

public ConsoleHostedService(ILogger<ConsoleHostedService> logger)
{
_logger = logger;
_logger.LogInformation("Created");
}

public async Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Started");
await Task.Yield();
_logger.LogInformation("ConsoleHostedService instance created...");
}

public async Task StopAsync(CancellationToken cancellationToken)
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Stopped");
await Task.Yield();
_logger.LogInformation("Hello from your hosted service thread!");
_logger.LogInformation("I may or may not return for a long time depending on what I do.");
_logger.LogInformation("In this example, I return right away, but my host will continue to run until");
_logger.LogInformation("its CancellationToken is Cancelled (SIGTERM(Ctrl-C) or a Lifetime Event )");
await Task.CompletedTask;
}
}
}
}
}

0 comments on commit d312930

Please sign in to comment.