在多个ninject绑定中重用SqlConnection

时间:2017-01-23 16:48:05

标签: c# sql dependency-injection ninject sqlconnection

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

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

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

DataConnection接受IDbConnection并返回一个Connection对象:

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

1 个答案:

答案 0 :(得分:2)

为您的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>());