-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathTestingServiceScope.cs
More file actions
66 lines (54 loc) · 2.02 KB
/
TestingServiceScope.cs
File metadata and controls
66 lines (54 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
namespace QueryKit.IntegrationTests;
using System.Threading.Tasks;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using WebApiTestProject.Database;
using static TestFixture;
public class TestingServiceScope
{
private readonly IServiceScope _scope;
public TestingServiceScope()
{
_scope = BaseScopeFactory.CreateScope();
}
public TScopedService GetService<TScopedService>() where TScopedService : notnull
{
var service = _scope.ServiceProvider.GetRequiredService<TScopedService>();
return service;
}
public async Task<TResponse> SendAsync<TResponse>(IRequest<TResponse> request)
{
var mediator = _scope.ServiceProvider.GetRequiredService<ISender>();
return await mediator.Send(request);
}
public async Task<TEntity?> FindAsync<TEntity>(params object[] keyValues)
where TEntity : class
{
var context = _scope.ServiceProvider.GetRequiredService<TestingDbContext>();
return await context.FindAsync<TEntity>(keyValues);
}
public async Task AddAsync<TEntity>(TEntity entity)
where TEntity : class
{
var context = _scope.ServiceProvider.GetRequiredService<TestingDbContext>();
context.Add(entity);
await context.SaveChangesAsync();
}
public async Task<T> ExecuteScopeAsync<T>(Func<IServiceProvider, Task<T>> action)
=> await action(_scope.ServiceProvider);
public Task<T> ExecuteDbContextAsync<T>(Func<TestingDbContext, Task<T>> action)
=> ExecuteScopeAsync(sp => action(sp.GetRequiredService<TestingDbContext>()));
public Task<int> InsertAsync<T>(params T[] entities) where T : class
{
return ExecuteDbContextAsync(db =>
{
foreach (var entity in entities)
{
db.Set<T>().Add(entity);
}
return db.SaveChangesAsync();
});
}
public TestingDbContext DbContext() => _scope.ServiceProvider.GetService<TestingDbContext>()!;
}