TLDR:如何在 Ninject 绑定(bind)中重用或实例化新的 Sql Connection 对象? ****第二次绑定(bind)失败**** 由于 SqlConnection 未初始化。我假设我无法跨多个绑定(bind)共享 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;
}
}
这是我的绑定(bind):
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),而不是实例化一个:
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>());
关于c# - 在多个 ninject 绑定(bind)中重用 SqlConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41811427/