Skip to content

Instantly share code, notes, and snippets.

@adamstirtan
Created October 26, 2023 14:10
Show Gist options
  • Select an option

  • Save adamstirtan/ef6439b8373d492c86419fd1ddd557ca to your computer and use it in GitHub Desktop.

Select an option

Save adamstirtan/ef6439b8373d492c86419fd1ddd557ca to your computer and use it in GitHub Desktop.
.NET console app using dependency injection and ILogger
using System;
using Microsoft.Extensions.DependencyInjection
using Microsoft.Extensions.Logging;
namespace MyApp
{
internal class Program
{
private static void Main(string[] args)
{
var services = CreateServices();
Application app = services.GetRequiredService<Application>();
app.MyLogic();
}
private static ServiceProvider CreateServices()
{
var serviceProvider = new ServiceCollection()
.AddLogging(options =>
{
options.ClearProviders();
options.AddConsole();
})
.AddSingleton<Application>(new Application())
.BuildServiceProvider();
return serviceProvider;
}
}
public class Application
{
private readonly ILogger<Application> _logger;
public Application(ILogger<Application> logger)
{
_logger = logger;
}
public void MyLogic()
{
_logger.LogInformation("Hello, World!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment