forked from oskardudycz/EventSourcing.NetCore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QueryHandler.cs
49 lines (43 loc) · 1.77 KB
/
QueryHandler.cs
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
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace ECommerce.Core.Queries;
public static class QueryHandler
{
public static IServiceCollection AddEntityFrameworkQueryHandler<TDbContext, TQuery, TResult>(
this IServiceCollection services,
Func<IQueryable<TResult>, TQuery, CancellationToken, Task<TResult>> handler
)
where TDbContext : DbContext where TResult : class
=>
services.AddQueryHandler<TQuery, TResult>(sp =>
{
var queryable =
sp.GetRequiredService<TDbContext>()
.Set<TResult>()
.AsNoTracking()
.AsQueryable();
return (query, ct) =>
handler(queryable, query, ct);
});
public static IServiceCollection AddEntityFrameworkQueryHandler<TDBContext, TQuery, TResult>(
this IServiceCollection services,
Func<IQueryable<TResult>, TQuery, CancellationToken, Task<IReadOnlyList<TResult>>> handler
)
where TDBContext : DbContext where TResult : class
=>
services.AddQueryHandler<TQuery, IReadOnlyList<TResult>>(sp =>
{
var queryable =
sp.GetRequiredService<TDBContext>()
.Set<TResult>()
.AsNoTracking()
.AsQueryable();
return (query, ct) =>
handler(queryable, query, ct);
});
public static IServiceCollection AddQueryHandler<TQuery, TResult>(
this IServiceCollection services,
Func<IServiceProvider, Func<TQuery, CancellationToken, Task<TResult>>> setup
) =>
services.AddTransient(setup);
}