AddDbContext<TContextService, TContextImplementation> don't use DI to create the db

Marco Segurini 21 Reputation points
2021-01-07T10:45:45.907+00:00

In my project I have created this DbContext derived class:

public class SqliteContext : DbContext, IRepoContext
{
    private readonly string _fullname;

    public SqliteContext()
    {
        _fullname = SqliteHelpers.CreateDbFullName();
    }

    public SqliteContext(IConfiguration configuration)
    {
        string connString = configuration.GetConnectionString("MyConnection");
        _fullname = connString;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        optionsBuilder.UseSqlite($@"Data Source={_fullname}");
    }

}

and I have updated the Startup class in this way:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IConfiguration>(x => Configuration);
        services.AddDbContext<IRepoContext, SqliteContext>();
    }

If I execute the "dotnet ef database update" command the default ctor of SqliteContext is used instead of the parametrized ctor.

If I don't use the interface

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IConfiguration>(x => Configuration);
        services.AddDbContext<SqliteContext>();
    }

all works fine, but isn't my case.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
725 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,621 Reputation points
    2021-01-08T02:38:41.99+00:00

    Hi MarcoSegurini-3410,
    Based on your code, it contains a parameterless constructor(SqliteContext()). Dependency injection will always choose the constructor with the least dependencies to be satisfied, which will be parameterless.
    So you can try to remove the parameterless constructor.
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.