CSharp · Console
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
public class Program
{
public static async Task Main()
{
var configBuilder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true);
var config = configBuilder.Build();
var sp = new ServiceCollection()
.AddLogging(b => b.AddConsole())
.AddSingleton<IConfiguration>(config)
.AddSingleton<IFooService, FooService>()
.BuildServiceProvider();
var logger = sp.GetService<ILoggerFactory>().CreateLogger<Program>();
logger.LogDebug("Starting");
var bar = sp.GetService<IFooService>();
await bar.DoAsync();
}
interface IFooService {
Task DoAsync();
}
class FooService : IFooService
{
private readonly ILogger<FooService> _logger;
public FooService(ILogger<FooService> logger)
{
_logger = logger;
}
public async Task DoAsync()
{
_logger.LogInformation("Working ...");
}
}
}