admin管理员组

文章数量:1122832

I am implementing an extension for EF Core. It will include:

  • an interceptor
  • changes to the schema
  • a custom convention

This means calling extension methods in DbContext.OnConfiguring (for the interceptor), DbContext.ConfigureConventions (for the convention), and DbContext.OnModelCreating (for the schema changes). For example:

public class MyContext :  DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.AddMySchemaChanges();
        base.OnModelCreating(modelBuilder);
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.AddMyInterceptor();
        base.OnConfiguring(optionsBuilder);
    }

    protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
    {
        configurationBuilder.AddMyConvention();
        base.ConfigureConventions(configurationBuilder);
    }
}

Now, I find this most inconvenient, and would like to have a single point where I invoke my extension method. But, this requires that I have access to the DbContext internals, for example, to where the conventions, interceptors, and model, are stored, and would probably be unsafe and not recommended (would like to avoid reflection, if possible). Something like:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.AddAllMyStuff();
    base.OnConfiguring(optionsBuilder);
}

This would even allow to configure all my stuff from the outside, e.g., from the AddDbContext method. Can anyone provide advice on this? Is there any pattern for dealing with this situation?

本文标签: netGetting EF Core Internal InformationStack Overflow