Skip to content

Instantly share code, notes, and snippets.

@fgbaezp
Created January 22, 2020 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fgbaezp/8fd538d7eb8929fed37f45e651d3668f to your computer and use it in GitHub Desktop.
Save fgbaezp/8fd538d7eb8929fed37f45e651d3668f to your computer and use it in GitHub Desktop.
ServiceStack multiple db connections
This is an example of one way to be able to use more than 1 db in a servicestack project.
Ref:
https://docs.servicestack.net/multitenancy
https://stackoverflow.com/a/26796083/8126179
https://stackoverflow.com/a/33329169/8126179
There is another way that's more elegant and involves creating specialized connectionfactories.
Ref:
https://stackoverflow.com/a/8766375/8126179
container.Register<IDbConnectionFactory>(
c => {
OrmLiteConnectionFactory dbFactory = new OrmLiteConnectionFactory(ConfigurationManager.ConnectionStrings["usuarios"].ConnectionString, SqlServerDialect.Provider)
{
ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
};
dbFactory.RegisterConnection("AnotherDB", ConfigurationManager.ConnectionStrings["Another"].ConnectionString, SqlServerDialect.Provider);
return dbFactory;
}
);
public class MyService : Service
{
public string Get(MyRequestModel request)
{
using (var db = DbFactory.OpenDbConnection("AnotherDB"))
{
var usersSellerQuery = @"select * from MyTable where id = '{0}'";
var usersSeller = db.SqlList<MyTable>(string.Format(usersSellerQuery, "5"));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment