Kyle
Kyle

Reputation: 5557

Reusing SqlConnection in multiple ninject bindings

TLDR: How do I re-using or instantiate a new Sql Connection object in my Ninject bindings? ****The second binding is failing**** due to SqlConnection is not initialized. I assume I can't share sql connection across multiple bindings?

I have a Sql repository in this pattern:

public class SqlRepository<T> : DataConnection, IRepository<T> where T : new() {
    public SqlRepository(IDbConnection connection) : base(connection)
}

DataConnection accepts an IDbConnection and returns a Connection object:

public class DataConnection : IDisposable {
    private IDbConnection _connection;

    public DataConnection(IDbConnection connection) {
        this._connection = connection;
    }

    protected IDbConnection Connection {
        get {
            if(_connection.state != ConnectionState.Open && _connection.state != ConnectionState.Connecting)
                _connection.Open();

            return _connection;
        }
    }
}

I'm re-using it in two places in one of my classes, depending on what type argument is passed, but the sql connection is the same:

public class WidgetsProvider {
    private readonly IRepository<Widget> _widgetsRepo;
    private readonly IRepository<Credential> _credentialRepo;

    public WidgetsProvider(IRepository<Widget> widgetsRepo, IRepository<Credential> credentialRepo) {
        _widgetsRepo = widgetsRepo;
        _credentialRepo = credentialRepo;
    }
}

Here are my bindings:

public class WidgetIocModule : Ninject.Modules.NinjectModule {
    public override void Load() {
        //get the sql connection
        var sql = new SqlConnection(ConfigurationManager.ConnectionStrings["widgetsConn"].ToString());

        //bind to repos
        Bind<IRepository<Widget>>().To<SqlRepository<Widget>>().InSingletonScope().WithConstructorArgument("connection", sql);
        Bind<IRepository<Credential>>().To<SqlRepository<Credential>>().InSingletonScope().WithConstructorArgument("connection", sql);
    }
}

Upvotes: 2

Views: 559

Answers (1)

Owen Pauling
Owen Pauling

Reputation: 11841

Create a binding for your SqlConnection rather than instantiating one:

Bind<SqlConnection>().ToConstant(new SqlConnection(ConfigurationManager.ConnectionStrings["widgetsConn"].ToString()));

Bind<IRepository<Widget>>().To<SqlRepository<Widget>>().InSingletonScope().WithConstructorArgument("connection", context => Kernel.Get<SqlConnection>());
Bind<IRepository<Credential>>().To<SqlRepository<Credential>>().InSingletonScope().WithConstructorArgument("connection", context => Kernel.Get<SqlConnection>());

Upvotes: 3

Related Questions