Base solution for your next web application
Open Closed

use multiple connection strings in HOST project #11692


User avatar
0
pliaspzero created

Hi,

I integrated costom .net Framework 4.8 project into *.Core.Shared - in my Framework 4.8 project I've multiple connection strings

To get it up and running - I needa to have these multiple connection strings in HOST project.

Could it be done like this?

  1. Update appsettings.json: Add your multiple connection strings in the "ConnectionStrings" section of your appsettings.json file:

json

"ConnectionStrings": { "DefaultConnection": "YourDefaultConnectionStringHere", "Database1Connection": "YourDatabase1ConnectionStringHere", "Database2Connection": "YourDatabase2ConnectionStringHere" }

Update ConfigureServices: Modify your ConfigureServices method to include the configuration for multiple connection strings. Below is an example of how you can do this:

csharp

public IServiceProvider ConfigureServices(IServiceCollection services) { // ... Existing code ...

// Register connection strings
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddDbContext<Database1Context>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("Database1Connection")));

services.AddDbContext<Database2Context>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("Database2Connection")));

// ... Existing code ...

}

In this example, I assumed that you're using Entity Framework Core for database access, and I've added ApplicationDbContext, Database1Context, and Database2Context as placeholders for your actual database contexts.

Using Connection Strings: Now you can inject these database contexts into your services or controllers and use them as needed. For example:

csharp

public class SomeService
{
    private readonly ApplicationDbContext _dbContext;
    private readonly Database1Context _db1Context;
    private readonly Database2Context _db2Context;

    public SomeService(ApplicationDbContext dbContext, Database1Context db1Context, Database2Context db2Context)
    {
        _dbContext = dbContext;
        _db1Context = db1Context;
        _db2Context = db2Context;
    }

    public void SomeMethod()
    {
        // Use _dbContext, _db1Context, and _db2Context here
    }
}

By following these steps, you can use multiple connection strings in your ASP.NET Core application. Remember to replace placeholders like "YourDefaultConnectionStringHere", "YourDatabase1ConnectionStringHere", and "YourDatabase2ConnectionStringHere" with your actual connection strings. Additionally, make sure to adjust the context classes and database access code according to your application's architecture.


1 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @pliaspzero

    Sorry, its my bad but I couldn't understand the question. Could you sum it up for me ?