【问题标题】:How to get ConnectionString Value from appsetting.json into Repository in Core WebAPI如何从 appsetting.json 获取 ConnectionString 值到核心 WebAPI 的存储库中
【发布时间】:2021-07-29 20:00:49
【问题描述】:

我是 Net Core WebAPI 的新手,我正在开发没有 EF 的 Core Web API。如果我无法将连接字符串从 appsetting.json 获取到我的存储库中,我就被卡住了

我已经创建了 CommonRepository 的构造函数并使用 IConfiguration 来获取连接字符串值

public CommonRepository(IConfiguration configuration)
    {
        _configuration = configuration;
    }
    private readonly IConfiguration _configuration;

但是在创建公共存储库的对象时它给出了一个错误

CommonRepository commonRepository =new CommonRepository();

没有给出与“CommonRepository.CommonRepository(IConfiguration)”所需的形参“configuration”相对应的参数

【问题讨论】:

  • 创建一个模型来存储连接字符串,在启动时从配置中填充它,并使用选项模式存储模型。在需要的地方注入模型并访问连接字符串。

标签: c# api asp.net-web-api .net-core asp.net-core-webapi


【解决方案1】:

您可以参考以下代码创建和使用CommonRepository,然后获取连接字符串。

CommonRepository:

public interface ICommonRepository
{
    string GetConnectionstring();
}

public class CommonRepository : ICommonRepository
{
    private readonly IConfiguration _configuration;
    public CommonRepository(IConfiguration configuration)
    {
        _configuration = configuration;
    }
    public string GetConnectionstring()
    {
        return _configuration.GetConnectionString("DefaultConnection");
    }
}

在 Startup.ConfigureServices 方法中注册上述仓库:

    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddScoped<ICommonRepository, CommonRepository>();
    }

控制器:

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly ICommonRepository _commonRepositoty;

    public HomeController(ILogger<HomeController> logger, ICommonRepository commonRepository)
    {
        _logger = logger;
        _commonRepositoty = commonRepository;
    }

    public IActionResult Index()
    {
        var str = _commonRepositoty.GetConnectionstring();
        return View();
    }

结果如下:

更多详细信息,请参阅Dependency injection in ASP.NET Core。

【讨论】:

    【解决方案2】:

    这通常使用依赖注入来完成,它应该在 startup.cs 文件中设置。因此:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
    
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IConfiguration>(Configuration);
        }
    
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            ...
        }
    }
    

    ASP.Net 会自动将配置从主机传递给这个类。我们使用它来创建一个单例,它将配置注入到所有使用 IConfiguration 作为参数的构造函数中。解释Here

    【讨论】:

      猜你喜欢
      • 2010-11-09
      • 2019-08-26
      • 2020-07-31
      • 2017-03-08
      • 2018-04-27
      • 1970-01-01
      • 2014-01-27
      • 2018-07-28
      • 1970-01-01
      相关资源
      最近更新 更多