【问题标题】:Get Connection String through Dependency Injection通过依赖注入获取连接字符串
【发布时间】:2019-06-16 20:51:57
【问题描述】:

我正在开发一个 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>();

但是在 DbConnector 类里面它说

字段初始化器不能引用非静态字段、方法或 属性 DbConnector.Configuration

请原谅我的编码模式,因为我是 DI 概念的新手。请建议是否有其他更好的方法来做到这一点。

【问题讨论】:

标签: c# asp.net-core .net-core blazor-server-side


【解决方案1】:

你犯了一个语法错误,这些应该是表达式体属性访问器。 ==&gt;

public string ConnectionString => Configuration.GetConnectionString();

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

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

【讨论】:

    【解决方案2】:
          services.AddConfiguration()  // enable Configuration Services
    
           var config = new WeblogConfiguration();
           Configuration.Bind("Weblog", config);      //  <--- This
           services.AddSingleton(config);
    

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
    猜你喜欢
    • 2023-01-21
    • 2017-08-20
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    相关资源
    最近更新 更多