我已经创建了一个使用服务层的控制台应用程序。
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));
}
我收到此错误System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger
1并且我猜测我必须为.NET Core Logging设置LoggerFactory和Microsoft.Extensions.Logging,但我无法做到做对了。
我在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());
有什么想法吗?
答案 0 :(得分:8)
应该有效:
var serviceProvider = new ServiceCollection()
.AddLogging() //<-- You were missing this
.BuildServiceProvider();
//get logger
var logger = serviceProvider.GetService<ILoggerFactory>()
.CreateLogger<Program>();
要安装的软件包: Microsoft.Extensions.DependencyInjection; Microsoft.Extensions.Logging;
答案 1 :(得分:-1)
如果您希望这样的.Net控制台应用程序具有Log4Net支持:
loggerFactory.AddLog4Net()
您将需要实现ILoggerProvider。我写了一篇文章,并编写了如何实现的代码: http://www.michalbialecki.com/2018/12/21/adding-a-log4net-provider-in-net-core-console-app/