如何从另一个项目访问连接字符串
我在 Visual Studio 2010 中的解决方案中有两个项目。
项目 1 包含一个带有 ConnectionString
的 app.config
。
如何从项目 2 访问该 ConnectionString
?
由于它们都使用相同的 ConnectionString
,因此我希望解决方案中只有一个实例。
I got two project in my solution in Visual Studio 2010.
Project 1 contains an app.config
with a ConnectionString
.
How can I access that ConnectionString
from Project 2?
Since they are both using the same ConnectionString
, I would prefer to only have one instance in my solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以将文件作为链接添加到您的某个文件项目。
使用
添加现有项目
到要添加文件的项目 -打开
按钮有一个向下的小箭头,如果单击该箭头,则可以选择添加作为链接
。这会将文件添加为原始位置的链接,这意味着您只有一个物理文件。
You can add the files as a link to the file to one of your projects.
Use
Add an Existing Item
to the project you want to add the file to - theOpen
button has a small down arrow, if you click that you can selectAdd as Link
.This will add the file as a link from the original location, meaning you only have one physical file.
另一个想法是使用 IoC 容器,例如 Ninject,将连接字符串注入到需要它的类的构造函数中。这与工厂模式没有什么不同。
参见这篇文章:
Ninject - 使用参数/实体框架连接字符串绑定构造函数
Another idea is to use an IoC container, like Ninject, injecting the connection-string into the constructor of the class you need it in. This is not unlike the factory pattern.
See this post:
Ninject - binding constructors with arguments / Entity Framework connection string
除了 Oded 答案中建议的文件链接之外,您还可以考虑重构应用程序以使用包含 DatabaseConnectionFactory 类等的通用数据访问程序集。该程序集将在其设置中包含连接字符串
Beside of the file linking suggested in the answer by Oded, you may consider refactoring your application to use a commom data access assembly that contains a DatabaseConnectionFactory class or the like. This assembly would contain the connection string in its settings
如果您只想共享特定部分(在您的情况下为connectionStrings),那么链接对您不起作用。相反,你可以这样做这样:
If there is only specific section you'd like to share (connectionStrings in your case) then linking wouldn't work for you. Instead you could do something like this:
如果您的项目 2 引用了项目 1,则项目 1 可能有一个公开了 ConnectionString 属性的类。
顺便说一句,“类”可以从 app.config 读取连接字符串
If your Project 2 has a reference of Project 1 then Project1 may have a class with a ConnectionString property exposed.
By the way, the "class" may read the connection string from the app.config