I am trying to implement CA in an ASP.NET Core Web API. Right now I have the presentation, infrastructure and application all set up, but when I tried Updating the Database with the DbContext Entities I have set up, I was met with this error:
Unable to create a 'DbContext' of type 'AppDbContext'. The exception 'The method or operation is not implemented.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
After some research I realized it was becouse even though within my .Presentation layer I was in fact configuring and referencing the AppDbContext within the .Infrastructure layer. It wasn't enough I needed to initialize it via a ContextFactory.
After a little bit more research I found a ContextFactory Model within the Ultimate ASP.NET Core book.
public class AppContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
public AppDbContext CreateDbContext(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<AppDbContext>()
.UseSqlServer(configuration.GetConnectionString("Default"),
b => b.MigrationsAssembly("Clean.Presentation"));
return new AppDbContext(builder.Options);
}
}
After implementing said ContextFactory within my Presentation layer I was surprised to see that the error when trying to update the Database kept appearing.
These are all of the relevant parts:
This is my AppDbContext Within my Infrastructure Layer:
public AppDbContext(DbContextOptions options) : base(options) { }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.ApplyConfiguration(new PersonaConfiguration());
//Initial Seeder
......
base.OnModelCreating(builder);
}
public DbSet<Usuario> Usuarios { get; set; } = null!;
public DbSet<Cargo> Cargos { get; set; } = null!;
public DbSet<CargoAsignado> CargoAsignados { get; set; } = null!;
public DbSet<Persona> Personas { get; set; } = null!;
}
As you can see pretty basic stuff.
This is The configuration within my Services Extensions in my .Presentation layer:
public static void ConfigureDbContext(this IServiceCollection services, IConfiguration config)
{
services.AddDbContext<AppDbContext>(options =>
{
options.UseSqlServer(config.GetConnectionString("Default"));
});
}
And its implementation within the Pipeline:
builder.Services.ConfigureDbContext(builder.Configuration);