diff --git a/src/Session/ISessionFactory.cs b/src/Session/ISessionFactory.cs new file mode 100644 index 0000000..e7c1f12 --- /dev/null +++ b/src/Session/ISessionFactory.cs @@ -0,0 +1,11 @@ +using System.Threading; +using System.Threading.Tasks; +using MongoDB.Driver; + +namespace MongoDB.Extensions.Session; + +public interface ISessionFactory +{ + ValueTask CreateSessionAsync( + CancellationToken cancellationToken); +} diff --git a/src/Session/Internal/MongoClientSessionFactory.cs b/src/Session/Internal/MongoClientSessionFactory.cs new file mode 100644 index 0000000..519d5c9 --- /dev/null +++ b/src/Session/Internal/MongoClientSessionFactory.cs @@ -0,0 +1,22 @@ +using System.Threading; +using System.Threading.Tasks; +using MongoDB.Driver; + +namespace MongoDB.Extensions.Session; + +internal class MongoClientSessionFactory : ISessionFactory +{ + private readonly IMongoClient _client; + + public MongoClientSessionFactory(IMongoClient client) + { + _client = client; + } + + public async ValueTask CreateSessionAsync( + CancellationToken cancellationToken) + { + return await _client + .StartSessionAsync(cancellationToken: cancellationToken); + } +} diff --git a/src/Session/Internal/MongoSessionProvider.cs b/src/Session/Internal/MongoSessionProvider.cs index b49f199..13d6f0f 100644 --- a/src/Session/Internal/MongoSessionProvider.cs +++ b/src/Session/Internal/MongoSessionProvider.cs @@ -6,14 +6,22 @@ namespace MongoDB.Extensions.Session; -public class MongoSessionProvider : ISessionProvider +public class MongoSessionProvider : MongoSessionProvider where TContext : IMongoDbContext { - private readonly IMongoClient _mongoClient; + public MongoSessionProvider(TContext context) + : base(new MongoClientSessionFactory(context.Client)) + { + } +} - public MongoSessionProvider(TContext context) +public class MongoSessionProvider : ISessionProvider +{ + private readonly ISessionFactory _sessionFactory; + + protected MongoSessionProvider(ISessionFactory sessionFactory) { - _mongoClient = context.Client; + _sessionFactory = sessionFactory; } protected virtual TransactionOptions TransactionOptions { get; } = new( @@ -25,8 +33,8 @@ public MongoSessionProvider(TContext context) public async Task BeginTransactionAsync( CancellationToken cancellationToken) { - IClientSessionHandle clientSession = await _mongoClient - .StartSessionAsync(cancellationToken: cancellationToken); + IClientSessionHandle clientSession = await _sessionFactory + .CreateSessionAsync(cancellationToken); clientSession.StartTransaction(TransactionOptions); @@ -36,9 +44,9 @@ public async Task BeginTransactionAsync( public async Task StartSessionAsync( CancellationToken cancellationToken) { - IClientSessionHandle clientSession = await _mongoClient - .StartSessionAsync(cancellationToken: cancellationToken); + IClientSessionHandle clientSession = await _sessionFactory + .CreateSessionAsync(cancellationToken); return new MongoSession(clientSession, TransactionOptions); } -} +} \ No newline at end of file