Есть Winforms приложение. в progrm.cs использую Host. При запуске ошибок не возникает, просто игнорируется BackgroundService класс. Хотя в asp core все бы работало. Помогите понять почему такое происходит.
program.cs
var host = Host.CreateDefaultBuilder()
.ConfigureAppConfiguration((context, builder) =>
{
builder.AddJsonFile("appsettings.json", optional: true);
})
.ConfigureServices((context, services) =>
{
services.AddHttpClient()
.AddDbContextFactory<DataContext>(opt => opt.UseMySql(
context.Configuration.GetConnectionString("MySQL"), Microsoft.EntityFrameworkCore.ServerVersion.Parse("5.7.30-mysql")
))
.AddLogging(configure => { configure.AddSerilog(); configure.SetMinimumLevel(LogLevel.Error | LogLevel.Warning); })
.AddHostedService<RabbitBackgroundService>()
.AddScoped<Form1>()
})
.ConfigureLogging(logging =>
{
})
.Build();
var services = host.Services;
var mainForm = services.GetRequiredService<Form1>();
using var db = services.GetRequiredService<IDbContextFactory<DataContext>>().CreateDbContext();
db.Database.Migrate();
Application.Run(mainForm);
Вот сам BackGroundService:
public class RabbitBackgroundService : BackgroundService
{
private IServiceScopeFactory _scopeService;
public RabbitBackgroundService( IServiceScopeFactory scopeFactory)
{
_scopeService = scopeFactory;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
using var scope = _scopeService.CreateScope();
var dbFactory = scope.ServiceProvider.GetService<IDbContextFactory<DataContext>>();
using var db = dbFactory.CreateDbContext();
var factory = new ConnectionFactory() { HostName = "...", UserName = "...", Password = "..." }; ;
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();
channel.ExchangeDeclare("shop_test", "direct", true);
channel.QueueDeclare(queue: "shop_test_buyers",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
channel.QueueBind("shop_test_buyers", "shop_test", "shop_test_buyers");
var telegramConsumer = new EventingBasicConsumer(channel);
telegramConsumer.Received += (ch, ex) =>
{
var body = ex.Body.ToArray();
var str = Encoding.UTF8.GetString(body, 0, body.Length);
var buyer = JsonSerializer.Deserialize<Buyer>(str);
Console.WriteLine(buyer);
//channel.BasicAck(ex.DeliveryTag, true);
//ex.DeliveryTag = true;
};
channel.BasicConsume("telegram", true, telegramConsumer);
return Task.CompletedTask;
}
}