Использование шаблона репозитория с Dapper и одним объектом доступа

Мы используем Dapper в качестве ORM и выбрали шаблон репозитория для организации наших операций. Это сработало для нас очень хорошо, но я хотел бы подтвердить, что эта конфигурация способна правильно разделять и удалять соединения SQL.

Startup.cs

services.AddScoped(_ => new DeploymentManagerDbConnection(
    new SqlConnection(Configuration.GetConnectionString("DeploymentManagement"))
));

services.AddScoped<IDeploymentManagerDbContext, DeploymentManagerDbContext>();
services.AddTransient<IChangeRequestRepository, ChangeRequestRepository>();
services.AddTransient<IBuildRepository, BuildRepository>();
services.AddTransient<IBatchRepository, BatchRepository>();
services.AddTransient<IUserRepository, UserRepository>();

DeploymentManagerDbConnection.cs

public DeploymentManagerDbConnection(IDbConnection dbConnection) : base(dbConnection)
{

}

DbConnection.cs

public class DbConnection : IDisposable
{
    private bool _disposed;

    public DbConnection(IDbConnection dbConnection)
    {
        Connection = dbConnection;
    }

    public IDbConnection Connection { get; }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
            if (disposing)
                Connection.Dispose();
        _disposed = true;
    }
}

DeploymentManagerDbContext.cs

public class DeploymentManagerDbContext : IDeploymentManagerDbContext
{
    private readonly IServiceProvider _serviceProvider;

    public DeploymentManagerDbContext(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public IChangeRequestRepository ChangeRequests =>
        _serviceProvider.GetService(typeof(IChangeRequestRepository)) as IChangeRequestRepository;

    public IBuildRepository Build =>
        _serviceProvider.GetService(typeof(IBuildRepository)) as IBuildRepository;

    public IBatchRepository Batch =>
        _serviceProvider.GetService(typeof(IBatchRepository)) as IBatchRepository;

    public IUserRepository Users =>
        _serviceProvider.GetService(typeof(IUserRepository)) as IUserRepository;
}

UserRepository.cs

public class UserRepository : IUserRepository
{
    private readonly IDbConnection _dbConnection;

    public UserRepository(DeploymentManagerDbConnection deploymentManagerDbConnection)
    {
        _dbConnection = deploymentManagerDbConnection?.Connection;
    }
}

0

Добавить комментарий

Ваш адрес email не будет опубликован.