我会亲自将所有连接字符串放在您的 App.Config 文件中并使用简单的 IOC 实现。
实际上,Nuget 的 ninject 包可能非常适合您的需求。
这就是我的意思。希望这使您的代码干净。我在以前的项目中使用了完全相同的模式,并且效果很好。
您可以更进一步,在您的 global.asax 中创建一个服务定位器并注册服务。如果您对此感兴趣,请告诉我。另请查看ninject。
public interface IService()
{
string GetConnectionString();
void DoStuff();
}
public class DBServiceOne : DbContext, IService
{
protected string GetConnectionString()
{
return ConfigurationManager.AppSettings["DBServiceOneConnectionString"]
}
public DBServiceOne(string str) : base(str)
{
this.Database.Connection.ConnectionString = GetConnectionString()
}
public void DoStuff() { //logic goes here }
}
public class DBServiceTwo : DbContext, IService
{
public DBServiceTwo(string str) : base(str)
{
this.Database.Connection.ConnectionString = GetConnectionString();
}
protected string GetConnectionString()
{
return ConfigurationManager.AppSettings["DBServiceTwoConnectionString"]
}
public void DoStuff() { //logic goes here }
}
public class DBServiceThree : DbContext, IService
{
public DBServiceThree(string str) : base(str)
{
this.Database.Connection.ConnectionString = GetConnectionString();
}
protected string GetConnectionString()
{
return ConfigurationManager.AppSettings["DBServiceThreeConnectionString"]
}
public void DoStuff() { //logic goes here }
}
现在实现——在你的控制器上使用构造函数注入
//This could be in your home controller
public class HomeController : AsyncController
{
private IService DBOneService;
private IService DBTwoService;
private IService DBThreeService;
public HomeController(IService one, IService two, IService three)
{
DBOneService= one;
DBTwoService = two;
DBThreeService = three;
}
public HomeController() : this(new DBServiceOne(), new DBServiceTwo(), new DBServiceThree()) {}
public ActionResult Index() {
DBOneService.DoStuff(); //here you'd want to return a list of data and serialize down with json or populate your razor template with it. Hope this helps!
}