feat: add data access DI helper

This commit is contained in:
Kyle 2024-07-05 20:03:12 -04:00
parent d079f12b16
commit 6cbccd3d7d
No known key found for this signature in database
GPG Key ID: 067C5D2D7C62E0F8
3 changed files with 27 additions and 9 deletions

View File

@ -1,30 +1,27 @@
using System.Data.Common;
using FruityFoundation.DataAccess.Abstractions;
using Microsoft.Extensions.DependencyInjection;
namespace FruityFoundation.DataAccess.Core;
public class DbConnectionFactory : IDbConnectionFactory
{
private readonly Func<DbConnection> _readWriteConnectionFactory;
private readonly Func<DbConnection> _readOnlyConnectionFactory;
private readonly IServiceProvider _serviceProvider;
public DbConnectionFactory(Func<DbConnection> readWriteConnectionFactory, Func<DbConnection> readOnlyConnectionFactory)
public DbConnectionFactory(IServiceProvider serviceProvider)
{
_readWriteConnectionFactory = readWriteConnectionFactory;
_readOnlyConnectionFactory = readOnlyConnectionFactory;
_serviceProvider = serviceProvider;
}
public INonTransactionalDbConnection<ReadWrite> CreateConnection()
{
var connection = _readWriteConnectionFactory();
var nonTxConnection = new NonTransactionalDbConnection<ReadWrite>(connection);
var nonTxConnection = _serviceProvider.GetRequiredService<INonTransactionalDbConnection<ReadWrite>>();
return nonTxConnection;
}
public INonTransactionalDbConnection<ReadOnly> CreateReadOnlyConnection()
{
var connection = _readOnlyConnectionFactory();
var nonTxConnection = new NonTransactionalDbConnection<ReadOnly>(connection);
var nonTxConnection = _serviceProvider.GetRequiredService<INonTransactionalDbConnection<ReadOnly>>();
return nonTxConnection;
}
}

View File

@ -22,6 +22,7 @@
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.1" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,20 @@
using System.Diagnostics.CodeAnalysis;
using FruityFoundation.DataAccess.Abstractions;
using Microsoft.Extensions.DependencyInjection;
namespace FruityFoundation.DataAccess.Core;
[ExcludeFromCodeCoverage(Justification = "Dependency injection helpers")]
public static class ServiceCollectionExtensions
{
public static void AddDataAccessCore(
this IServiceCollection services,
Func<IServiceProvider, INonTransactionalDbConnection<ReadWrite>> readWriteConnectionImplementationFactory,
Func<IServiceProvider, INonTransactionalDbConnection<ReadOnly>> readOnlyConnectionImplementationFactory
)
{
services.AddTransient<INonTransactionalDbConnection<ReadWrite>>(readWriteConnectionImplementationFactory);
services.AddTransient<INonTransactionalDbConnection<ReadOnly>>(readOnlyConnectionImplementationFactory);
services.AddSingleton<IDbConnectionFactory, DbConnectionFactory>();
}
}