tgstation-server  4.3.2
The /tg/station 13 server suite
DatabaseContextFactory.cs
Go to the documentation of this file.
1 using Microsoft.Extensions.DependencyInjection;
2 using System;
3 using System.Threading.Tasks;
4 
5 namespace Tgstation.Server.Host.Database
6 {
9  {
13  readonly IServiceScopeFactory scopeFactory;
14 
19  public DatabaseContextFactory(IServiceScopeFactory scopeFactory)
20  {
21  this.scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory));
22 
23  using var scope = scopeFactory.CreateScope();
24  scope.ServiceProvider.GetRequiredService<IDatabaseContext>();
25  }
26 
28  public async Task UseContext(Func<IDatabaseContext, Task> operation)
29  {
30  if (operation == null)
31  throw new ArgumentNullException(nameof(operation));
32 
33  using var scope = scopeFactory.CreateScope();
34  await operation(scope.ServiceProvider.GetRequiredService<IDatabaseContext>()).ConfigureAwait(false);
35  }
36  }
37 }
Factory for scoping usage of IDatabaseContexts. Meant for use by Components
async Task UseContext(Func< IDatabaseContext, Task > operation)
Run an operation in the scope of an IDatabaseContext
readonly IServiceScopeFactory scopeFactory
The IServiceScopeFactory for the DatabaseContextFactory
DatabaseContextFactory(IServiceScopeFactory scopeFactory)
Construct a DatabaseContextFactory