I have a Web API 2 using Dapper.net, and it's accessed by various client with their own database. Currently, I'm using custom header called Client-Id
to identify the client.
This Client-Id
contains a ConnectionString
name and I passed this connection string into my constructor.
Here's my project structure:
Api.Persentation -> Api.Service -> Api.Logic
The connection string will pass from Api.Persentation
to Api.Logic
as follows:
Api.Persentation
public string testApi()
{
//using the service
//consider the connection string was handled on base class
var _myService = new testApiService(base.ConnectionString);
return _myService.HelloWorld();
}
Api.Service
public class testApiService: BaseService
{
#region const
//This class was from API.Logic
private readonly testApiRepo _testApiRepo;
//the connectionString passed into base class to use a log repo
public testApiService(string connectionString)
: base(connectionString)
{
this._testApiRepo = new testApiRepo(connectionString);
}
#endregion
public string HelloWorld()
{
//access API.Logic
return this._testApiRepo.GetHelloWorld();
}
}
Api.Logic
It has two classes, where BaseConnection
is an abstract class to open the connection (the class how I use ConnectionString
). The second one is, testApiRepo
showing how I use the connection to get a database value.
/*-------------
BaseConnection Class
-------------*/
public abstract class BaseConnection
{
private string _connectionString;
public BaseConnection(string ConnectionString)
{
this._connectionString = ConnectionString;
}
public MyDbConnection GetOpenConnection(bool mars = false)
{
string cs = this._connectionString;
if (mars)
{
SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(cs);
scsb.MultipleActiveResultSets = true;
cs = scsb.ConnectionString;
}
//Finally we use the connection string in here
var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[this._connectionString].ToString());
MyDbConnection DbConnection = new MyDbConnection(connection);
DbConnection.Open();
return DbConnection;
}
}
/*-------------
testApiRepo Class
-------------*/
public class testApiRepo : BaseConnection
{
#region Const
//the connection will handled on base class
public CommissionRepo(string connectionString)
: base(connectionString)
{
}
#endregion
public string GetHelloWorld()
{
//using base class to open connection
using (var _db = base.GetOpenConnection())
{
string query = "SELECT 'HelloWorld'";
var result = _db.Query<string>(query);
return result.FirstOrDefault();
}
}
}