views:

80

answers:

3

I'm just writing some data access code. I've decided to pass in the name of connection string from the config via constructor injection which the repository then reads and uses to construct a SqlConnectionStringBuilder.

Thinking about it I probably don't need the SqlConnectionStringBuilder but that's a different matter.

Should I be reading the configuration here or should that be confined to client code? Opinions?

public class SqlRepository : IRepository
{
    private SqlConnectionStringBuilder _connString;

    public SqlRepository(string connectionStringName)
    {
        var connStringSetting = ConfigurationManager.ConnectionStrings[connectionStringName];

        if (connStringSetting == null)
            throw new ArgumentException("Could not find connection string in configuration.");

        _connString = new SqlConnectionStringBuilder(connStringSetting.ConnectionString);
    }

}
+2  A: 

I'd perfer to pass an actual connection string (or even Dependency Inject it). Doing so helps maintaining SoC and SRP.

Anton Gogolev
A: 

Could different clients use different connection strings? If so I'd read the config in the client and pass it through. If all clients will require the same connection strinn then keep that information in the data layer.

Steve Haigh
A: 

IF you pass the connection string into the DAL, you are making something out side of the data layer aware of the data base, which is a layer violation. Nothing outside of the DAL should have any knowledge of anything DB related, if you want to have the client set what connection string to use, then have them set the configuration, nothing more.

If you want to decouple the connection string use the factory pattern, and let it worry about what connection string to use, single responsibility principal. You can use dependency injection, config file, etc.

Bob The Janitor