I will try to explain my situation as best as possible and I hope it makes sense.
My project is a .NET core Web API. With a seperate class library project which contains models including my DbContext stuff.
Problem #1 I want to be able to Log to console from within Startup.cs
Reason: I am currently debugging setting a variable from an environment variable. I want to output what has been set to console.
Example: How do I write logs from within Startup.cs
Now, the solution was to add ILoggerFactory to the Service container in Program.cs as such:
var host = new WebHostBuilder()
.UseKestrel()
.ConfigureServices(s => {
s.AddSingleton<IFormatter, LowercaseFormatter>();
})
.ConfigureLogging(f => f.AddConsole(LogLevel.Debug))
.UseStartup<Startup>()
.Build();
host.Run();
Next, change Startup.cs constructor to take in ILoggerFactory that will be taken from the container that we just registered. As follows:
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.");
}
This solved my problem - I can run the application and it works fine now, logging where I need it.
HOWEVER.
When I then attempt to run dotnet ef database update --startup-project=myAPIProject
It now fails, because EF does not go via Program.cs, it instead attempts to directly instantiate my Startup class. And because now my constructor requires an ILoggerFactory, EF doesn't know what to do and throws an exception.
Does anyone know a way around this issue?