【发布时间】:2017-07-16 07:30:37
【问题描述】:
我会尽量解释我的情况,我希望这是有道理的。
我的项目是一个 .NET 核心 Web API。使用一个单独的类库项目,其中包含模型,包括我的 DbContext 东西。
问题 #1 我希望能够从 Startup.cs 中登录到控制台
原因:我目前正在调试从环境变量设置变量。我想将设置的内容输出到控制台。
示例:How do I write logs from within Startup.cs
现在,解决方案是将 ILoggerFactory 添加到 Program.cs 中的 Service 容器中:
var host = new WebHostBuilder()
.UseKestrel()
.ConfigureServices(s => {
s.AddSingleton<IFormatter, LowercaseFormatter>();
})
.ConfigureLogging(f => f.AddConsole(LogLevel.Debug))
.UseStartup<Startup>()
.Build();
host.Run();
接下来,更改 Startup.cs 构造函数以接收 ILoggerFactory,这将从我们刚刚注册的容器中获取。如下:
public class Startup {
ILogger _logger;
IFormatter _formatter;
public Startup(ILoggerFactory loggerFactory, IFormatter formatter){
_logger = loggerFactory.CreateLogger<Startup>();
_formatter = formatter;
}
public void ConfigureServices(IServiceCollection services) {
_logger.LogDebug($"Total Services Initially: {services.Count}");
// register services
//services.AddSingleton<IFoo, Foo>();
}
public void Configure(IApplicationBuilder app, IFormatter formatter) {
// note: can request IFormatter here as well as via constructor
_logger.LogDebug("Configure() started...");
app.Run(async (context) => await context.Response.WriteAsync(_formatter.Format("Hi!")));
_logger.LogDebug("Configure() complete.");
}
这解决了我的问题 - 我可以运行应用程序,它现在可以正常工作,记录我需要的地方。
但是。
当我尝试运行 dotnet ef database update --startup-project=myAPIProject
它现在失败了,因为 EF 不通过 Program.cs,而是尝试直接实例化我的 Startup 类。而且因为现在我的构造函数需要 ILoggerFactory,所以 EF 不知道该做什么并引发异常。
有人知道解决这个问题的方法吗?
【问题讨论】:
标签: entity-framework asp.net-core entity-framework-core