Home > Back-end >  How to use 2 different connection string for read and for writes in postgre with CQRS?
How to use 2 different connection string for read and for writes in postgre with CQRS?

Time:09-29

In our project we are using .net 5.0 with CQRS with postgre. Our all apps are containerized and runs on kubernetes. For postgre we have master -> slave configuration with pgpool ( for writes), for reads it is directly getting from slaves but pgpool configured before master node.

Is it possible to configure for CQRS (MediatR) using one connection for read and another connection for write?

My DI configuration looks like:

        services.AddDbContext<DataContext>(opt =>
        {
            opt.EnableDetailedErrors();
            opt.UseLazyLoadingProxies();
            opt.UseNpgsql(configuration.GetConnectionString("TaikunConnection"),
                options =>
                {
                    options.MigrationsAssembly(typeof(DataContext).Assembly.FullName);
                    options.EnableRetryOnFailure();
                    options.CommandTimeout((int)TimeSpan.FromMinutes(10).TotalSeconds);
                });
        });

        services.AddScoped<IDataContext>(provider => provider.GetService<DataContext>());

        var builder = services.AddIdentityCore<User>()
            .AddEntityFrameworkStores<DataContext>();

        var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);
        identityBuilder.AddSignInManager<SignInManager<User>>();
        identityBuilder.AddUserManager<UserManager<User>>();

CodePudding user response:

You can use 2 different context:

services.AddDbContext<DataWriteContext>(opt =>
        {
            opt.EnableDetailedErrors();
            opt.UseLazyLoadingProxies();
            opt.UseNpgsql(configuration.GetConnectionString("TaikunConnectionForWrite"),
                options =>
                {
                    options.MigrationsAssembly(typeof(DataContext).Assembly.FullName);
                    options.EnableRetryOnFailure();
                    options.CommandTimeout((int)TimeSpan.FromMinutes(10).TotalSeconds);
                });
        });

services.AddDbContext<DataReadContext>(opt =>
        {
            opt.EnableDetailedErrors();
            opt.UseLazyLoadingProxies();
            opt.UseNpgsql(configuration.GetConnectionString("TaikunConnectionForRead"),
                options =>
                {
                    options.MigrationsAssembly(typeof(DataContext).Assembly.FullName);
                    options.EnableRetryOnFailure();
                    options.CommandTimeout((int)TimeSpan.FromMinutes(10).TotalSeconds);
                });
        });
  • Related