Rob Stevenson-Leggett
Rob Stevenson-Leggett

Reputation: 35689

Configuration reading, should it be confined to client code?

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);
    }

} 

Upvotes: 0

Views: 124

Answers (3)

Bob The Janitor
Bob The Janitor

Reputation: 20802

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.

Upvotes: 0

Steve
Steve

Reputation: 8511

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.

Upvotes: 0

Anton Gogolev
Anton Gogolev

Reputation: 115859

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

Upvotes: 2

Related Questions