I've created a console application using Microsoft.Extensions.Logging that uses a service layer.
Program.cs
public static void Main(string[] args)
{
// Create service collection
var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection);
// Create service provider
var serviceProvider = serviceCollection.BuildServiceProvider();
// Entry to run app
serviceProvider.GetService<App>().Run().RunSynchronously();
}
private static void ConfigureServices(IServiceCollection serviceCollection)
{
// Configuration
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false)
.Build();
serviceCollection.AddOptions();
serviceCollection.Configure<Settings>(options =>
{
//...
});
// Services
serviceCollection.AddTransient<IOneService, OneService>();
serviceCollection.AddTransient<ISecondService, SecondService>();
// Repositories
serviceCollection.AddTransient<MyContext, MyContext>();
serviceCollection.AddTransient<IOneRepository, OneRepository>();
// App
serviceCollection.AddTransient<App>();
// Logger
// Automapper
serviceCollection.AddSingleton(new AutoMapperProfileConfiguration());
serviceCollection.AddScoped<IMapper>(sp =>
new Mapper(sp.GetRequiredService<IConfigurationProvider>(), sp.GetService));
}
I'm getting this error
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1
and I'm guessing that i have to setup LoggerFactory and Microsoft.Extensions.Logging
for .NET Core Logging, but I can't get it right.
I've tried something like this in Main():
// Attempt 1
ILoggerFactory loggerFactory = new LoggerFactory()
.AddConsole()
.AddDebug();
ILogger logger = loggerFactory.CreateLogger<Program>();
logger.LogInformation(
"This is a test of the emergency broadcast system.");
// Attempt 2
serviceCollection.AddSingleton(new LoggerFactory()
.AddConsole()
.AddDebug());
Any ideas?
.AddLogging()
on the service collection to add that functionality to the container. – Mirza