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

for*_*umb 4 c# connection-string entity-framework-core .net-6.0 worker-service

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

有人知道这里出了什么问题吗?下面是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();
Run Code Online (Sandbox Code Playgroud)

Gur*_*ron 8

IHostBuilder.ConfigureServices接受带有两个参数的操作,第一个参数是HostBuilderContext公开配置属性(您使用的参数来自HostingHostBuilderExtensions),因此请尝试:

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