I've created a console application 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?
It is designed as a logging API that developers can use to capture built-in ASP.NET logging as well as for their own custom logging. The logging API supports multiple output providers and is extensible to potentially be able to send your application logging anywhere.
Logging levels are used to filter logging output, tailoring the amount of data output to the situation in hand. Each logging level is associated with the type of data logged. DEBUG, INFO, and TRACE events are typically non-error conditions that report on the behavior of an application.
It should work:
var serviceProvider = new ServiceCollection()
.AddLogging() //<-- You were missing this
.BuildServiceProvider();
//get logger
var logger = serviceProvider.GetService<ILoggerFactory>()
.CreateLogger<Program>();
Packages to install : Microsoft.Extensions.DependencyInjection; Microsoft.Extensions.Logging;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With