连接的Ninject和请求范围

时间:2012-07-11 21:55:14

标签: database asp.net-mvc-3 database-connection ninject

在请求完成后,请求范围是否与我的DatabaseFactory绑定发布我的数据库连接?

kernel.Bind<IDatabaseFactory>().To<DatabaseFactory<MySqlConnection>>().InRequestScope().WithConstructorArgument("connectionString", Config.Data.MySQLConnection);


public class DatabaseFactory<T> : Disposable, IDatabaseFactory where T : IDbConnection, new()
    {
        private readonly string _connectionString;
        private  IDbConnection _dataConnection;

        public DatabaseFactory(string connectionString)
        {
            _connectionString = connectionString;
        }

        #region IDatabaseFactory Members

        public IDbConnection Get()
        {
            return _dataConnection ?? (_dataConnection = new T { ConnectionString = _connectionString });
        }

        #endregion

        protected override void DisposeCore()
        {
            if (_dataConnection != null)
                _dataConnection.Dispose();
        }
}

1 个答案:

答案 0 :(得分:2)

如果您使用Ninject.Web.MVC扩展名,那么一旦垃圾收集器(GC)收集请求对象(来自here

,就会保证这些对象被处理掉