Take the 2-minute tour ×

I'm looking for a way to inject my connections into my repositories. I tried to inject the SqlConnection using the IDBConnection, but I got some problems when NInject tries to deactivate the connection, the event is never called. And I cannot figure out how to inject the connection string into my repositories.

Could someone provide me a suggestion?

share|improve this question
You will have to provide more information and probably a code sample. –  Jeff Jan 25 '13 at 19:25

2 Answers 2

up vote 9 down vote accepted

I use NInject to perform the Dependency Injection of my projects. I usually end with the configuration below:

Simple Factory Interface

public interface IDbConnectionFactory
    IDbConnection CreateConnection();

Factory Implementation

public class SqlConnectionFactory : IDbConnectionFactory
    private readonly string _connectionString;

    public SqlConnectionFactory(string connectionString)
        _connectionString = connectionString;

    public IDbConnection CreateConnection()
        var conn = new SqlConnection(_connectionString);
        return conn;

NInject Config:


Example of a repository:

public class UserRepository : IUserRepository
    private readonly IDbConnectionFactory _dbConnectionFactory;

    public UserRepository(IDbConnectionFactory dbConnectionFactory)
        _dbConnectionFactory = dbConnectionFactory;

    public IEnumerable<User> List()
        using (var dbConnection = _dbConnectionFactory.CreateConnection())

Edit: I always let the ADO.NET take care of connection pooling. So I open and close the connection every single time that I need to perform a database operation.

This approach is working for me and is very simple as you mentioned in your question.

share|improve this answer
The complete example I was looking for. I will accept the answer as soon as SO allow me. Thank you dude. –  user2011100 Jan 25 '13 at 14:01

Inject a wrapper class:

class ConnectionProvider { public SqlConnection Get() { ... } }

You can add an interface to it if you want.

Using this pattern you can also inject the connection string, if you like:

class ConnectionStringProvider { public string Get() { ... } }
share|improve this answer
Thank you usr! If I could I will vote to your answer. –  user2011100 Jan 25 '13 at 14:02

Your Answer

