在EF的DbContext多个字符串连接 [英] Multiple string connections in EF DbContext

查看:1669
本文介绍了在EF的DbContext多个字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发基于codePLEX EFMVC解决方案MVC网站,我使用实体框架和信息库,工作和Command模式的单位。我的网站需要一个SaaS解决方案(软件即服务)多个数据库。
在我的遗产Asp.Net的WebForms我有一个包含所有不同的字符串连接一个XML文件,我试图用同样的策略。所以在我的LoginController我创建一个具有公司的命令(以确定在哪个数据库将要连接)的用户名和密码。在验证中域项目()方法,我在读取XML获得基于企业领域的正确的字符串连接。我的问题是我怎么能设置DatabaseFactory或的DbContext使用此选择连接字符串?它应该在构造函数中注入?任何建议以正确的方式做这个,没有打破规则?

I’m developing a MVC Website based in codeplex EFMVC solution, and I’m using Entity Framework and Repository, Unit of Work and Command Patterns. My website needs to be a SaaS solution (software as a service) multiple database. In my legacy Asp.Net WebForms I have a XML file that holds all the different string connections and I’m trying to use the same strategy. So in my LoginController I create a command that has company (to identify in which database will be connected) username and password. At Validate() method in Domain project, I’m reading the XML to get the correct string connection based on company field. My problem is how can I set the DatabaseFactory or DbContext to use this selected connection string? It should be injected at the constructor? Any suggestion for doing this in the correct way, without "breaks the rules"?

请注意,我使用AutoFac的依赖注入。

Note that I’m using AutoFac for Dependency Injection.

谢谢您的关注。

最良好的祝愿,

路易斯·费尔南多·瓦尔Dionizio

Luiz Fernando Vall Dionizio

推荐答案

您可以使用Autofaq的ResolveNamed功能来获取不同的注册相同的接口
例如:

You can use the ResolveNamed feature of Autofaq to get different registration for the same Interface For instance:

 builder.Register<IDataContext>(x => new DataContext(connectionStringOne))
          .Named<IDataContext>("CS1");

 builder.Register<IDataContext>(x => new DataContext(connectionStringTwo))
          .Named<IDataContext>("CS2");

和解决它。

var context = ContainerAccessor.Container().ResolveNamed<IDataContext>("CS1"); 

另一种方法是从该请求的共享位置覆盖的DataContext构造函数和读取配置

Another way is to override the DataContext ctor and read the configuration from an shared location for that request.

这篇关于在EF的DbContext多个字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆