如何在Castle ActiveRecord中引用SqlConnection(或连接字符串)?

时间:2009-10-01 09:20:41

标签: c# castle-activerecord castle

如何在config中引用当前的SqlConnection或Sqlconnection?

我找到了http://svn.castleproject.org:8080/svn/castle/trunk/ActiveRecord/Castle.ActiveRecord.Tests/DifferentDatabaseScopeTestCase.cs

和代码

 private string GetSqlConnection()
        {
            IConfigurationSource config = GetConfigSource();

            IConfiguration db2 = config.GetConfiguration(typeof(ActiveRecordBase));

            string conn = string.Empty;

            foreach (IConfiguration child in db2.Children)
            {
                if (child.Name == "connection.connection_string")
                {
                    conn = child.Value;
                }
            }

            return conn;
        }

但我不明白我在哪里可以找到“GetConfigSource”实现?这是标准的城堡助手功能吗?

我使用这些名称空间

using Castle.ActiveRecord;
using NHibernate.Criterion;
using NHibernate;
using Castle.Core.Configuration;
using Castle.ActiveRecord.Framework;

4 个答案:

答案 0 :(得分:3)

var sfimpl = ActiveRecordMediator.GetSessionFactoryHolder()
                                 .GetSessionFactory(typeof(object));
IDbConnection conn = ((ISessionFactoryImplementor)sfimpl)
                        .ConnectionProvider.GetConnection();

答案 1 :(得分:1)

我在我的项目中使用它:

 public static MySqlConnection GetConnection()
    {
        if (_session == null)
        {
            _session = ActiveRecordMediator.GetSessionFactoryHolder().CreateSession(typeof(ActiveRecordBase));
        }
        var connection = (MySqlConnection)_session.Connection;
        if (connection.State == ConnectionState.Closed)
            connection.Open();
        //var connection = new MySqlConnection(Connstr);
        //connection.Open();
        return connection;
    }

    public static void CloseActiveIsession()
    {
        if (_session != null)
        {
            ActiveRecordMediator.GetSessionFactoryHolder().ReleaseSession(_session);
        }
    }

答案 2 :(得分:0)

我发现获取字符串的方法是:

    public static string GetConnectionString() {
        using (var session = ActiveRecordMediator
                            .GetSessionFactoryHolder()
                            .GetSessionFactory(typeof(ActiveRecordBase))
                            .OpenSession())
        {
            return session.Connection.ConnectionString;
        }
    }

打开会话以获取连接字符串可能效率低下。还有其他地方可以找到吗?

答案 3 :(得分:-1)

我不得不从svn中加载AR来源来解决它。

这意味着

System.Configuration.ConfigurationManager.GetSection("activerecord") as IConfigurationSource;