Код: Выделить всё
public class Program
{
private static IConfigurationRoot _apiConfiguration = null!;
public static async Task Main(string[] args)
{
try
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (environment == Environments.Development)
{
_apiConfiguration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
}
else
{
_apiConfiguration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
}
await CreateHostBuilder(args).Build().RunAsync();
}
catch (Exception ex)
{
// log
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(loggingBuilder =>
{
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(_apiConfiguration) // This throws System.NullReferenceException: 'Object reference not set to an instance of an object.' as _apiConfiguration is null
.Enrich.FromLogContext()
.Enrich.WithProperty("ApplicationName", "WeatherAPI")
.WriteToOtlpSerilog()
.CreateLogger();
loggingBuilder.AddSerilog();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
});
}
Код: Выделить всё
[TestClass]
public class WeatherControllerTests : WebApplicationFactory
{
[TestMethod]
public async Task TestAsync()
{
var client = CreateClient();
var response = await client.GetAsync("/weather/getforecast");
Assert.IsNotNull(response);
}
}
Подробнее здесь: https://stackoverflow.com/questions/796 ... configurat