tgstation-server
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;
5 
6 namespace Tgstation.Server.Host.Core
7 {
10  {
14  readonly IServiceScopeFactory scopeFactory;
15 
20  public DatabaseContextFactory(IServiceScopeFactory scopeFactory)
21  {
22  this.scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory));
23 
24  using (var scope = scopeFactory.CreateScope())
25  scope.ServiceProvider.GetRequiredService<IDatabaseContext>();
26  }
27 
29  public async Task UseContext(Func<IDatabaseContext, Task> operation)
30  {
31  if (operation == null)
32  throw new ArgumentNullException(nameof(operation));
33 
34  using (var scope = scopeFactory.CreateScope())
35  await operation(scope.ServiceProvider.GetRequiredService<IDatabaseContext>()).ConfigureAwait(false);
36  }
37  }
38 }
Factory for scoping usage of IDatabaseContexts. Meant for use by Components
DatabaseContextFactory(IServiceScopeFactory scopeFactory)
Construct a DatabaseContextFactory
readonly IServiceScopeFactory scopeFactory
The IServiceScopeFactory for the DatabaseContextFactory
async Task UseContext(Func< IDatabaseContext, Task > operation)
Run an operation in the scope of an IDatabaseContext