My method should not call ApplyAsync() if the service is not registered. I'm trying to add a conditional null, but I still get a null reference at the moment the method is called. Am I doing something wrong?
private static async Task ApplyMigrationsAsync(CancellationToken token)
{
using var scope = Startup.ServiceProvider.CreateScope();
var migration = scope.ServiceProvider.GetService<M.Migrations.IMigration>();
await migration?.ApplyAsync(token);
}
Applying conditionala access ?
and awaiting the result will end in awaiting null
. Which cannot be awaited.
Guard your access with an if
statement and await inside the if
block:
private static async Task ApplyMigrationsAsync(CancellationToken token)
{
using var scope = Startup.ServiceProvider.CreateScope();
var migration = scope.ServiceProvider.GetService<M.Migrations.IMigration>();
if (migration != null)
{
await migration.ApplyAsync(token);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.