In my last post, we discussed how to run a Sql script from C# to insert lookup data when we regenerate our database for integration tests. But we want to make sure that the connection string that’s being used by NHibernate is the same connection string being used by our InsertTestData() method. To do that, we can use reflection to find the value of the ConnectionString property of the ISessionFactory.ConnectionProvider object.

public static class NHibernateHelper
{
    private static readonly ISessionFactory _sessionFactory = Configuration.BuildSessionFactory();
    private static Configuration _configuration;
    public static ISessionFactory SessionFactory
    {
        get { return _sessionFactory; }
    }
    public static Configuration Configuration
    {
        get
        {
            if (_configuration == null)
                _configuration = new Configuration().Configure();
            return _configuration;
        }
    }
    public static string ConnectionString
    {
        get
        {
            var propertyType = typeof (DriverConnectionProvider);
            var propertyInfo = propertyType.GetProperty("ConnectionString"
                                                , BindingFlags.Instance | BindingFlags.NonPublic);
            return (string) propertyInfo.GetValue(SessionFactory.ConnectionProvider, null);
        }
    }
    public static ISession GetSession()
    {
        var session = _sessionFactory.OpenSession();
        session.FlushMode = FlushMode.Never;
        return session;
    }
}

Now we can change the InsertTestData() method to use this connection string.

public void InsertTestData()
{
    using (var conn = new SqlConnection(NHibernateHelper.ConnectionString))
    {
        FileInfo fileInfo = new FileInfo(@"Sql\InsertSeedData.sql");
        var sql = fileInfo.OpenText().ReadToEnd();
        Server server = new Server(new ServerConnection(conn));
        server.ConnectionContext.ExecuteNonQuery(sql);
    }
}

Update:

Matt pointed out below that we really don’t need to use reflection to do this, NHibernate handles it for us. Thanks Matt!
public static string ConnectionString
{
    get
    {
        return Configuration.GetProperty("connection.connection_string");
    }
}

DotNetKicks Image