繁体   English   中英

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

[英]Connection strings in .NET 6 Worker service

我正在尝试使用写在 appsetting.json 中的连接字符串连接到数据库。 我尝试在 AddDbContext 中的 UseSqlServer("...") 中传递它,但它不起作用。 当我在上下文 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接受带有两个参数的操作,第一个是HostBuilderContext公开配置属性(您使用的来自HostingHostBuilderExtensions ),所以尝试:

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

非常感谢,我得到了 ConnString,但它仍然无法连接到 Db。 我想我也必须做点别的。

当我像下面的代码那样做时,它可以工作。

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

            if (!optionsBuilder.IsConfigured)
            {
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
                optionsBuilder.UseSqlServer(configuration.GetConnectionString("nbiot_core_svctest"));
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM