Do not call the method if the service is not registered

Viewed 37

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);
    }
1 Answers

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);
        }
    }

Related