-
Notifications
You must be signed in to change notification settings - Fork 0
Creating a UnitOfWork
StrutTower edited this page Jul 4, 2024
·
1 revision
Start by installing the Nuget package for the database you will be connecting to.
- MySQL -
Install-Package TowerSoft.Repository.MySql - SQL Server -
Install-Package TowerSoft.Repository.MicrosoftSql - SQLite -
Install-Package TowerSoft.Repository.SQLite
Next, create the UnitOfWork class. This handles the connection to the database. I normally create this in the Repository folder of my class library project.
public class UnitOfWork : UnitOfWorkBase {
public UnitOfWork(IConfiguration config) {
DbAdapter = new MySqlDbAdapter(config.GetConnectionString("default"));
// ^ Change the DbAdapter based on the type of database you are connecting to
}
// Stores the repositories that have already been initialized
private readonly Dictionary<Type, object> repos = new Dictionary<Type, object>();
public TRepo GetRepo<TRepo>() where TRepo : IDbRepository {
Type type = typeof(TRepo);
if (!repos.ContainsKey(type)) repos[type] = Activator.CreateInstance(type, this);
return (TRepo)repos[type];
}
}Important
The UnitOfWork should then be added to your dependency injection services as a scoped service so it can be easily access and automatically disposed of when a request is finished.