Base solution for your next web application
Open Closed

One connectionstring for read/write, one for read? #6791


User avatar
0
tomop created

Running .NET Core 2.2, v6.5.0

We use Azure for our SQL Server database which comes with read only replicas. We can access a replica instance specifically by specifying the following attribute in the connection string - ApplicationIntent=ReadOnly

Right now we are using multi-tenancy with one database only.

Do you have any suggestion how we could target read operations at one connection string and everything else goes to the default connection string?


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

    Hi @tomop

    There is no such implementation by default. You can define an attribute (for Get only) and use it the operations you want to use read-only database.

    Then, you need to implement a custom connection string resolver like this one https://github.com/aspnetboilerplate/aspnetboilerplate/blob/dev/src/Abp/Domain/Uow/DefaultConnectionStringResolver.cs. In your implementation, get the http context and find if the called action has the attribute you defined or not. (you can also check the name of the method and if it starts with Get, you can assume it as Get).

    Then, you can return the connection string you want accordingly. Just note that, in this approach, only one single database will be used according the entry point of the request.

    You can override the SaveChanges method of the read only DbContext and throw exception if you are planning to use two different connection strings.