C# 通过依赖项注入获取连接字符串

C# 通过依赖项注入获取连接字符串,c#,asp.net-core,.net-core,blazor-server-side,C#,Asp.net Core,.net Core,Blazor Server Side,我正在开发blazor应用程序。我希望在类中有连接字符串和其他一些键作为服务 为此,我创建了一个接口 interface IDbConnector { string ConnectionString { get; set; } bool SomeKey { get; set; } } 在我的课堂上,我想要这样的东西 using Microsoft.Extensions.Configuration; public class DbConnector : IDbConne

我正在开发blazor应用程序。我希望在类中有连接字符串和其他一些键作为服务

为此,我创建了一个接口

interface IDbConnector
{
    string ConnectionString { get; set; }

    bool SomeKey { get; set; }
}
在我的课堂上,我想要这样的东西

using Microsoft.Extensions.Configuration;
    public class DbConnector : IDbConnector
    {
        private IConfiguration Configuration { get; set; }

        public DbConnector(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public string ConnectionString = Configuration.GetConnectionString();

        public bool SomeKey = Configuration.GetSection("xyz");
    }
我可以将其注册为服务

services.AddScoped<IDbConnector, DbConnector>();
services.addScope();
但在DbConnector类中,它说

fiels初始值设定项不能引用非静态字段、方法或 属性DbConnector.Configuration

请原谅我的编码模式,因为我是新的DI概念。请建议是否有其他更好的方法来执行此操作。

services.AddConfiguration()//启用配置服务
      services.AddConfiguration()  // enable Configuration Services

       var config = new WeblogConfiguration();
       Configuration.Bind("Weblog", config);      //  <--- This
       services.AddSingleton(config);
var config=new WeblogConfiguration();
Configuration.Bind(“Weblog”,config);// 您犯了语法错误,这些应该是表达式体属性访问器<代码>=
=>

public string ConnectionString => Configuration.GetConnectionString();

public bool SomeKey => Configuration.GetSection("xyz");

相反,您尝试将它们初始化为字段。字段初始化预构造函数,因此无法访问配置。

您可以执行
ConnectionString=configuration.GetConnectionString()在构造函数中。@JohanP,错误:ConnectionString在当前上下文中不存在。您需要声明它<代码>公共字符串连接字符串{get;set;}
的可能重复,而此代码可能会回答此问题,提供有关此代码为什么和/或如何回答此问题的其他上下文,从而提高其长期价值。