Inject multiple Idbconnection into Asp.Net core

Asked

Viewed 71 times

0

Good morning, you guys, all right?

I need to inject 2 Dbcontext into Asp.net core and I’m having problems with it. Follow the code example.

    string defaultConnectionA = _configuration.GetConnectionString("defaultConnectionA");
    services.AddTransient<IDbConnection>(x => new SqlConnection(defaultConnectionA));

    string defaultConnectionB = _configuration.GetConnectionString("defaultConnectionB");
    services.AddTransient<IDbConnection>(x => new SqlConnection(defaultConnectionB));

Doing so, he leaves only the last as active.

I tried to create a new interface and inherited from "Idbconnection", however, it did not work.

Can someone help me?

thank you abs

1 answer

0

all right?

You can use an EF Core extension, in which case you need to define your contexts by inheriting from Dbcontext:

Use like this:

   services.AddDbContext<DbContext1>(options =>
        {
            options.UseSqlServer(Configuration["ConnectionString1"],
                                 sqlServerOptionsAction: sqlOptions =>
                                 {
                                     sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                                     //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency 
                                     sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                                 });
        });

  services.AddDbContext<DbContext2>(options =>
            {
                options.UseSqlServer(Configuration["ConnectionString2"],
                                     sqlServerOptionsAction: sqlOptions =>
                                     {
                                         sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                                         //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency 
                                         sqlOptions.EnableRetryOnFailure(maxRetryCount: 10, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
                                     });
            });

The sqlServerOptionsActions settings can be removed, but in the case of the example, the first treats the setting where Migrations will be managed (In the case in my project I always use the "Application" layer and the second is a Retry policy treatment, in case I use the cloud then it is necessary because of the latency.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.