4

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();
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
forrestDumb
  • 57
  • 1
  • 7
  • 1
    "it just doesn't work": any error message? Or output? Usually setting up connection string looks like `options.UseSqlServer(config.GetConnectionString("key_name_in_appsettings"));` – paradise Dec 02 '21 at 12:34
  • Program runs without errors. I just want to somehow get connection string in UseSqlServer() that is written in appsettings.json but I dont know how. I found some solutions but those are all for older versions of .NET and I am using .NET 6 – forrestDumb Dec 02 '21 at 12:47

1 Answers1

8

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"));
})
Guru Stron
  • 102,774
  • 10
  • 95
  • 132