在多个 ninject 绑定中重用 SqlConnection

Reusing SqlConnection in multiple ninject bindings

TLDR:如何在我的 Ninject 绑定中重新使用或实例化一个新的 Sql 连接对象? ****第二个绑定失败**** 由于 Sql连接未初始化。我想我不能在多个绑定之间共享 sql 连接?

我有一个 Sql 这种模式的存储库:

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

DataConnection 接受一个 IDbConnection 和 returns 一个连接对象:

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

我在我的 类 之一的两个地方重新使用它,具体取决于传递的类型参数,但 sql 连接是相同的:

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

这是我的绑定:

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

为您的 SqlConnection 创建绑定而不是实例化绑定:

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