.NET 6 Worker 服务中的连接字符串

Connection strings in .NET 6 Worker service

我正在尝试使用 appsetting.json 中编写的连接字符串连接到数据库。我尝试在 AddDbContext 的 UseSqlServer("...") 中传递它,但它不起作用。当我在 Context class 中编写它时,它起作用了。 所以,程序运行没有错误,但它没有连接到 Db。

有人知道这里出了什么问题吗? 下面是 Program.cs 代码:

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

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

.ConfigureServices((ctx, services)=>
{
    services
        ...
        .AddDbContext<nbiot_core_svctestContext>(
        options => options.UseSqlServer(ctx.Configuration.GetConnectionString("DefaultConnection"));
})