My ASP.Net MVC application has to connect to multiple databases at run time. I can overload my class to accept the connection string at run time as shown below
class MyClassDBContext:DbContext
{
public MyClassDBContext(string str) : base(str)
{
this.Database.Connection.ConnectionString = str;
}
}
Currently, I am retrieving this connection string from a database table. My workflow is as follows
- Website connects to default database using credentials stored in
web.config - Website queries default database to get connection strings for
other databases. - Websites connects to other databases by supplying the connection
string at run time
The problem I facing right now is in keeping my code clean. Every time I need the connection string for database number 2, I have to look it up in the default database. Is there any cleaner way of doing this? I considered storing the connection string in the profile data but I am not sure if this is a good idea. Every user of my website will need to connect to at most 2-3 different databases depending on their credentials.
I would personally put all connection strings in your App.Config file and use a simple IOC implementation.
Actually the ninject package off Nuget might be perfect for your needs.
Here’s what I mean though. Hopefully this makes your code clean. I used this exact same pattern for a previous project and it worked out well.
You could take it a step further and make a Service Locator and register services in your global.asax. Let me know if that interests you. Also check out ninject.
Now for the implementation — Use Constructor Injection on your controllers