-
Notifications
You must be signed in to change notification settings - Fork 0
/
Worker.cs
85 lines (75 loc) · 2.72 KB
/
Worker.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using TestEF.Entities;
namespace TestEF
{
public class Worker(IHostApplicationLifetime hostApplicationLifetime, IServiceProvider serviceProvider)
: IHostedService, IHostedLifecycleService
{
Task IHostedLifecycleService.StartingAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
async Task IHostedService.StartAsync(CancellationToken cancellationToken)
{
await DoWork(cancellationToken);
}
Task IHostedLifecycleService.StartedAsync(CancellationToken cancellationToken)
{
hostApplicationLifetime.StopApplication();
return Task.CompletedTask;
}
Task IHostedLifecycleService.StoppingAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
Task IHostedService.StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
Task IHostedLifecycleService.StoppedAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
private async Task DoWork(CancellationToken cancellationToken)
{
var scope = serviceProvider.CreateScope();
var databaseContext = scope.ServiceProvider.GetRequiredService<DatabaseContext>();
await databaseContext.Database.MigrateAsync(cancellationToken);
var guids = new List<Guid>()
{
Guid.Parse("83B58C48-A296-450B-BD76-CE0A658EC38E")
};
var messages = await databaseContext.Messages
.Where(x => guids.Contains(x.Uid))
.ToListAsync(cancellationToken);
foreach (var message in messages)
{
Console.WriteLine(JsonConvert.SerializeObject(message));
}
}
private async Task<ChatEntity> CreateChat(DatabaseContext databaseContext, string name)
{
var chat = new ChatEntity
{
Uid = Guid.NewGuid(),
Name = name
};
databaseContext.Chats.Add(chat);
await databaseContext.SaveChangesAsync();
return chat;
}
private async Task AddMessage(DatabaseContext databaseContext, Guid chatUid, string text)
{
databaseContext.Messages.Add(new MessageEntity
{
Uid = Guid.NewGuid(),
Text = text,
ChatUid = chatUid,
});
await databaseContext.SaveChangesAsync();
}
}
}