Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connection strings in .NET 6 Worker service

I am trying to connect to database with connection string which is written in appsetting.json. I try to pass it in UseSqlServer("...") in AddDbContext but it just doesn't work. When I write it in Context class it works. So, program runs without errors but it doesn't connect to Db.

Does someone know what is wrong here? Below is Program.cs code:

using IHost host = Host.CreateDefaultBuilder(args)
    .UseWindowsService(options =>
    {
        options.ServiceName = "Subscriber Service";
    })
    .ConfigureServices(services =>
    {
        services.AddHostedService<DeliveryService>()
            .AddSingleton<IQueueService, QueueService>()
            .AddSingleton<IMailTransport, MailTransport>()
            .AddSingleton<IHttpTransport, HttpTransport>()
            .AddDbContext<nbiot_core_svctestContext>(
            options => options.UseSqlServer("name=ConnectionStrings:DefaultConnection"));
    })
    .Build();

await host.RunAsync();
like image 451
forrestDumb Avatar asked Sep 16 '25 22:09

forrestDumb


1 Answers

IHostBuilder.ConfigureServices accepts an action with two parameters, the first one is HostBuilderContext exposing configuration property (the one you are using comes from HostingHostBuilderExtensions), so try:

.ConfigureServices((ctx, services)=>
{
    services
        ...
        .AddDbContext<nbiot_core_svctestContext>(
        options => options.UseSqlServer(ctx.Configuration.GetConnectionString("DefaultConnection"));
})
like image 192
Guru Stron Avatar answered Sep 19 '25 12:09

Guru Stron