Created
January 22, 2020 20:29
-
-
Save fgbaezp/8fd538d7eb8929fed37f45e651d3668f to your computer and use it in GitHub Desktop.
ServiceStack multiple db connections
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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