Search code examples
c#entity-framework-coreconnection-string.net-6.0worker-service

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();

Solution

  • 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"));
    })