How to Access a connectionstring from another project
I got two project in my solution in Visual Studio 2010.
Project 1 con开发者_开发技巧tains anapp.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.
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 - the Open
button has a small down arrow, if you click that you can select Add as Link
.
This will add the file as a link from the original location, meaning you only have one physical file.
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.
Note: you don't need to be using Entity Framework to use Ninject.
See this post: Ninject - binding constructors with arguments / Entity Framework connection string
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
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:
The solution is to store the connection strings on the web.config of the parent web app.
Note that the web site root is also an app, so you can store a web.config in there (i.e. c:\inetpub\wwwroot\web.config) which will be inherited by all apps under it.
c:\inetpub\wwwroot\web.config -> common configuration.
c:\inetpub\wwwroot\app1\web.config -> configuration for app1
c:\inetpub\wwwroot\app2\web.config -> configuration for app2.
In the case the default web site root is off limits, you can create a root app to contain all other apps and store the common configuration there.
c:\inetpub\wwwroot\myrootapp\web.config-> common configuration. c:\inetpub\wwwroot\myrootapp\app1\web.config -> configuration for app1 c:\inetpub\wwwroot\myrootapp\app2\web.config -> configuration for app2.
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
精彩评论