aboutsummaryrefslogtreecommitdiff
path: root/docker/crupest-api/CrupestApi/CrupestApi.Commons/Crud/CrudService.cs
blob: 9402d69bb4b3ed1d42af293588b597bae6cd323c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using System.Data;
using Dapper;
using Microsoft.Extensions.Options;

namespace CrupestApi.Commons.Crud;

// TODO: Implement and register this service.
public class CrudService<TEntity> : IDisposable
{
    protected readonly TableInfo _table;
    protected readonly IDbConnection _dbConnection;
    protected readonly IOptionsSnapshot<CrupestApiConfig> _crupestApiOptions;
    private readonly ILogger<CrudService<TEntity>> _logger;

    public CrudService(ITableInfoFactory tableInfoFactory, IDbConnectionFactory dbConnectionFactory, IOptionsSnapshot<CrupestApiConfig> crupestApiOptions, ILogger<CrudService<TEntity>> logger)
    {
        _table = tableInfoFactory.Get(typeof(TEntity));
        _dbConnection = dbConnectionFactory.Get();
        _crupestApiOptions = crupestApiOptions;
        _logger = logger;

        if (!_table.CheckExistence(_dbConnection))
        {
            DoInitializeDatabase(_dbConnection);
        }
    }

    public virtual void DoInitializeDatabase(IDbConnection connection)
    {
        using var transaction = connection.BeginTransaction();
        connection.Execute(_table.GenerateCreateTableSql(), transaction: transaction);
        transaction.Commit();
    }

    public void Dispose()
    {
        _dbConnection.Dispose();
    }
}