Home > Net >  ASP.NET Core : Why do we need IDesignTimeDbContextFactory?
ASP.NET Core : Why do we need IDesignTimeDbContextFactory?

Time:08-13

I have an ASP.NET Core application and all I have is the DataContext, I don't have IDesignTimeDbContextFactory implemented.

public class DataContext : DbContext, IUnitOfWork
{...}

With that I can do Add-Migration, Update-Database & Script-Migration.

However, I came across an another project where they have implemented IDesignTimeDbContextFactory, mentioned that this is to generate migration classes.

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<CodingBlastDbContext>
{
    public CodingBlastDbContext CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();

        var builder = new DbContextOptionsBuilder<CodingBlastDbContext>();

        var connectionString = configuration.GetConnectionString("DefaultConnection");

        builder.UseSqlServer(connectionString);

        return new CodingBlastDbContext(builder.Options);
    }
}

I wonder why this is needed? especially the first project works without implementing the IDesignTimeDbContextFactory..

CodePudding user response:

Docs have some explanation on when you can leverage the design-time factory:

A design-time factory can be especially useful if you need to configure the DbContext differently for design time than at run time, if the DbContext constructor takes additional parameters are not registered in DI, if you are not using DI at all, or if for some reason you prefer not to have a CreateHostBuilder method in your ASP.NET Core application's Main class.

The only use case I personally encountered was when DbContext was moved into a separate library and we did not want to run CreateHostBuilder for context designing purposes (startup involved some relatively heavy stuff and we didn't want to invoke that). Like for example here.

  • Related