I have a class within my web application that handles all my database access. Currently I have a class property to which that I pass 开发者_如何转开发in the database connection string stored in the web.config. Is this the best way or is there a better method to use? Thanks.
You can add a key into appSettings
block of web.config
file. For example:
<appSettings>
<add key="connectionString" value="Data Source=xxx;ID=yyy;Initial Catalog=zzz; Password=ppp;"/>
</appSettings>
Inside your code you can use this setting like following:
using System.Configuration;
.....
.....
private string connectionString = ConfigurationManager.AppSettings["connectionString"];
This way is excellent when you should access your connection string from different modules in one solution.
If the connection string is mandatory (which it probably is, since we're talking a data access class), I personally prefer to pass in the connection string/connection settings object in the constructor of the class.
If you're creating an abstracted data access layer you might consider passing in a ConnectionStringSettings object instead in order to be able to use the ADO.NET provider model to create the right type of ADO objects based on the provider type of the connection.
Passing a settings object instead of a string also helps if you are using Dependency Injection. That way the object can be automatically resolved by the IoC container.
As far as I know (and have seen), this is the most adopted approach for maintaining a connection string. So yes, I would say storing connection string in a web.config
file is fine.
精彩评论