-
Notifications
You must be signed in to change notification settings - Fork 4
Home
Install via the NuGet package. The package follows Semantic Versioning
Most methods are based off the IDatabaseConnection
interface, and it's complementary IDatabase
and IDatabaseUnitOfWork
interfaces. IDatabaseConnection
contains the data access methods, whilst IDatabase
and IDatabaseUnitOfWork
contain methods related to managing the connection itself, e.g. transaction commit or rollback.
When using the repository pattern, the lifetime of the IDatabase or IDatabaseUnitOfWork is expected to be inside of a single method. Typically you should define an interface, IDatabaseProvider and inject that into your repository.
public interface IDatabaseProvider
{
IDatabase Open();
IDatabaseUnitOfWork StartUnitOfWork();
}
public class UserRepository
{
private readonly IDatabaseProvider databaseProvider;
public UserRepository(IDatabaseProvider databaseProvider)
{
this.databaseProvider = databaseProvider;
}
public User GetUser(int id)
{
using (var database = this.databaseProvider.Open())
{
return database.Get<User>(id);
}
}
}
The database provider is usually easy to define yourself, but is so variable in possible use-cases and implementations that this project doesn't attempt to define a default one. However, you may be able to use this example for .Net Framework and SQL client, customizing it for your needs:
public interface IDatabaseProvider
{
IDatabase Open();
IDatabaseUnitOfWork StartUnitOfWork();
}
public class DefaultDatabaseProvider
: IDatabaseProvider
{
public IDatabase Open()
{
var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"];
if (connectionString == null)
{
throw new InvalidOperationException("MyConnectionString not found");
}
IDbConnection connection = null;
try
{
connection = new SqlConnection(connectionString);
connection.Open();
return new DefaultDatabase(connection, PeregrineConfig.SqlServer2012);
}
catch
{
connection?.Dispose();
throw;
}
}
public IDatabaseUnitOfWork StartUnitOfWork()
{
IDatabase database = null;
try
{
database = this.Open();
return database.StartUnitOfWork(false);
}
catch
{
database?.Dispose();
}
}
}