An error occurred while accessing the Microsoft.Extensions.Hosting services when do first migrations

EF calls CreateWebHostBuilder or BuildWebHost without running Main. So Iconfiguration is null.

Create new class which inherited from IDesignTimeDbContextFactory .

public class YourDbContext : DbContext
{
//Dbcontext implementation
}

public class YourDbContextFactory : IDesignTimeDbContextFactory<YourDbContext>
{
    public YourDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<YourDbContext>();
        optionsBuilder.UseSqlServer("your connection string");

        return new YourDbContext(optionsBuilder.Options);
    }
}

You are using a new .net core EF which uses IHostBuilder.(in an older version like yours the provider is IWebHostBuilder).

The tools first try to obtain the service provider by invoking the Program.CreateHostBuilder(), calling Build(), then accessing the Services property.

You can learn more about Design-time DbContext Creation from Here

It may happen from a condition in your startup file or while you are injecting. for example, you have a flag that checks if some variable in appsettings is true to use inmemory database instance.

EF needs to build the model and use the DbContext without starting the application. When EF invokes methods, your config services are still null that’s why you get an error.

Make sure you have installed the package

Microsoft.EntityFrameworkCore.Tools

Leave a Comment