C# 扩展DbContext以避免代码重复

C# 扩展DbContext以避免代码重复,c#,entity-framework-core,C#,Entity Framework Core,我有一个包含多个DbContext类的项目:每个域一个。由于EF Core并不完美,我必须向每个DbContext添加一些功能,比如允许它处理SQL Server 2017的新JSON功能。我还添加了其他功能,但为了简洁起见,我已将其从示例中删除 要将此JSON功能添加到每个DbContext,我使用BasedDBContext,它是一个简单扩展DbContext的抽象类。该功能的先决条件之一是拦截发送到数据库的SQL查询。为了实现这一点,我使用了所描述的策略 在接下来的几周里,我们将进入不同的

我有一个包含多个DbContext类的项目:每个域一个。由于EF Core并不完美,我必须向每个DbContext添加一些功能,比如允许它处理SQL Server 2017的新JSON功能。我还添加了其他功能,但为了简洁起见,我已将其从示例中删除

要将此JSON功能添加到每个DbContext,我使用BasedDBContext,它是一个简单扩展DbContext的抽象类。该功能的先决条件之一是拦截发送到数据库的SQL查询。为了实现这一点,我使用了所描述的策略

在接下来的几周里,我们将进入不同的开发环境,我希望通过选项模式基于当前环境注入正确的连接字符串。这与拦截战术不符。因为调用了执行拦截
GetService()
,这实际上会在继续我的SomeDbContext的构造函数之前触发OnConfigurang函数,这意味着我的选项永远不会被填充,从而导致NullReferenceException

如何在不触发onconfig的情况下扩展DbContext,同时避免代码重复?我也可以运行自定义EF核心,但如果可能的话,我希望避免这种情况

public abstract class BaseDbContext : DbContext, IBaseDbContext
{
    protected BaseDbContext()
    {
        DiagnosticListener listener = this.GetService<DiagnosticSource>() as DiagnosticListener; // This calls OnConfiguring.
        listener.SubscribeWithAdapter(new JsonInterceptor());
    }

    [DbFunction("JSON_VALUE", "")]
    public static string JsonValue(string source, string path)
    {
        throw new NotSupportedException();
    }

    [DbFunction("TRY_CAST", "")]
    public static string TryCast(string source, string typeName)
    {
        throw new NotSupportedException();
    }
}

public class SomeDbContext : BaseDbContext, ISomeDbContext
{
    private readonly SomeDbContextOptions _options;

    public DbSet<Order> Orders { get; set; }

    public SomeDbContext(IOptions<SomeDbContextOptions> options)
    {
        _options = options.Value;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // This is called before _options is set meaning it is null in the line below.
        optionsBuilder
            .UseSqlServer(_options.ConnectionString);
    }
}
公共抽象类BaseDbContext:DbContext,IBaseDbContext
{
受保护的BaseDbContext()
{
DiagnosticListener=this.GetService()作为DiagnosticListener;//这将调用OnConfigurang。
subscribowithadapter(新的JsonInterceptor());
}
[DbFunction(“JSON_值,”“)]
公共静态字符串JsonValue(字符串源、字符串路径)
{
抛出新的NotSupportedException();
}
[DbFunction(“TRY_CAST”,”)]
公共静态字符串TryCast(字符串源,字符串类型名)
{
抛出新的NotSupportedException();
}
}
公共类SomeDbContext:BaseDbContext、ISomeDbContext
{
私有只读SomeDbContextOptions\u选项;
公共数据库集命令{get;set;}
公共SomeDbContext(IOOptions选项)
{
_选项=选项.值;
}
配置时受保护的覆盖无效(DBContextOptions Builder Options Builder)
{
//这是在设置_options之前调用的,这意味着它在下面的行中为null。
选项生成器
.UseSqlServer(_options.ConnectionString);
}
}