Problem upgrading .net 3.1 to .net 8, context.GetService cannot be used inside OnModelCreating

I am trying to transfer my whole project from .net 3.1 to .net 8.
I have resolved some smaller issues but have encountered this major issue which stops me from completing the transition.

What i have in the project is support for both Postgres and SQL Server. Depending on settings in appsettings we register either Postgres or SQL Server database.

        private static void AddDb(this ContainerBuilder builder, ProjectSettings settings)
        {
            switch (settings.DbType)
            {
                case DbTypeEnum.Postgres:
                    {
                        builder.RegisterAssemblyModules(typeof(Postgres.AutofacModule).Assembly);
                        break;
                    }
                case DbTypeEnum.SqlServer:
                    {
                        builder.RegisterAssemblyModules(typeof(SqlServer.AutofacModule).Assembly);
                        break;
                    }
            }
        }

Because of this, i have a parent DB context, and two separate context classes for both Postgres and SQL Server.

In both of those classes there is some custom setup for each of those databases. The main part of the problem is when i am trying to override OnModelCreating to add a custom function for comparison.

In .net 3.1 this code works without a problem, but in .net 8 i am getting an error:

An attempt was made to use the model while it was being created. A DbContext instance cannot be used inside ‘OnModelCreating’ in any way that makes use of the model that is being created.

It seems that in .net 5 they changed how this used to work.

In parent class of DbContext i have this:


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
        }

Code for SQL Server is this:

 public sealed class SqlServerContext : ParentDbContext
 {
     public static string SCHEMA = "dbo";
     public SqlServerContext(DbContextOptions options, ICurrentUser currentUser) : base(options, currentUser)
     {

     }

     protected override void OnModelCreating(ModelBuilder modelBuilder)
     {
         modelBuilder.HasDefaultSchema(SCHEMA);

         base.OnModelCreating(modelBuilder);

         AddCustomFunctions(modelBuilder);
     }

     private void AddCustomFunctions(ModelBuilder modelBuilder)
     {
         MethodInfo likeMethod = typeof(CustomFunctions)
            .GetMethod(nameof(CustomFunctions.Like), new[] { typeof(string), typeof(string) });

         var sqlExpressionFactory = this.GetService<ISqlExpressionFactory>();

         modelBuilder.HasDbFunction(likeMethod).HasTranslation(expressions =>
         {
             var expression = expressions.ElementAt(0); 
             var pattern = expressions.ElementAt(1); 

             return sqlExpressionFactory.Like(expression, pattern);
         });
     }

AddCustomFunctions for Postgres looks like this:

private void AddCustomFunctions(ModelBuilder modelBuilder)
{
    MethodInfo likeMethod = typeof(CustomFunctions)
       .GetMethod(nameof(CustomFunctions.Like), new[] { typeof(string), typeof(string) });

    var sqlExpressionFactory = (NpgsqlSqlExpressionFactory)this.GetService<ISqlExpressionFactory>();

    modelBuilder.HasDbFunction(likeMethod).HasTranslation(expressions =>
    {
        var expression = expressions.ElementAt(0);
        var pattern = expressions.ElementAt(1);

        return sqlExpressionFactory.ILike(expression, pattern);
    });
}

CustomFunctions looks like this:

    public class CustomFunctions
    {
        public static bool Like(string expression, string pattern)
            => throw new InvalidOperationException("this method should not be called client side");
    }

The point of CustomFunctions and mapping this is so throughout the code i can do this for both database types, for example lets say we have a company table:

Context.Companies.FirstOrDefaultAsync(x => CustomFunctions.Like(x.Name, $"%{name}%"));

I have tried to resolve this problem in several ways through Dependency Injection but without success. Trying to pass ISqlExpressionFactory all the way to both Postgres and SQL Server contexts, but no success.
I tried to bring in IServiceProvider or IServiceProviderFactory directly to call the GetService method, but I get an error that they are not registered through DI, which doesn’t make sense because they should be registered during Autofac registration.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật