Skip to content

Instantly share code, notes, and snippets.

@crmckenzie
Last active December 17, 2015 02:19
Show Gist options
  • Save crmckenzie/5534975 to your computer and use it in GitHub Desktop.
Save crmckenzie/5534975 to your computer and use it in GitHub Desktop.
How I setup my NHibernate configuration to use Sqlite for unit tests.
public static void ConfigureToUseSqlite(this IKernel kernel)
{
var nHibernateConfiguration = Substitute.For<INHibernateConfiguration>(); // custom interface
var msSqlConfiguration = SQLiteConfiguration.Standard
.InMemory()
.ShowSql()
;
nHibernateConfiguration.GetPersistenceConfiguration().Returns(msSqlConfiguration);
kernel.Rebind<INHibernateConfiguration>()
.ToConstant(nHibernateConfiguration)
.Named("MyNamedDatabaseConfiguration")
;
var configuration = kernel.Get<global::NHibernate.Cfg.Configuration>("MyNamedDatabaseConfiguration");
configuration.Properties["connection.provider"] = typeof(PersistentInMemorySqliteConnectionProvider).AssemblyQualifiedName;
var session = kernel.Get<ISession>("MyNamedDatabaseConfiguration");
var schemaExport = new SchemaExport(configuration);
schemaExport.Execute(script: true, export: true, justDrop: false, connection: session.Connection, exportOutput: Console.Out);
}
public class PersistentInMemorySqliteConnectionProvider : DriverConnectionProvider
{
private IDbConnection _persistentConnection;
public override void CloseConnection(System.Data.IDbConnection conn)
{
// do nothing
}
public override System.Data.IDbConnection GetConnection()
{
EnsurePersistentConnection();
return _persistentConnection;
}
private void EnsurePersistentConnection()
{
if (_persistentConnection == null)
{
var sqliteConnection = new SQLiteConnection("Data Source=:memory:;Version=3;New=True;");
sqliteConnection.Open();
_persistentConnection = sqliteConnection;
}
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (_persistentConnection != null)
{
_persistentConnection.Dispose();
_persistentConnection = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment