C# 如何将ConnectionString值从appsetting.json获取到Core WebAPI中的存储库中
我是网络核心WebAPI的新手,我正在开发没有EF的核心WebAPI。我被卡住了,因为我无法将appsetting.json中的连接字符串获取到我的存储库中 我已经创建了CommonRepository的构造函数,并使用IConfiguration获取连接字符串值C# 如何将ConnectionString值从appsetting.json获取到Core WebAPI中的存储库中,c#,api,asp.net-web-api,.net-core,asp.net-core-webapi,C#,Api,Asp.net Web Api,.net Core,Asp.net Core Webapi,我是网络核心WebAPI的新手,我正在开发没有EF的核心WebAPI。我被卡住了,因为我无法将appsetting.json中的连接字符串获取到我的存储库中 我已经创建了CommonRepository的构造函数,并使用IConfiguration获取连接字符串值 public CommonRepository(IConfiguration configuration) { _configuration = configuration; } private
public CommonRepository(IConfiguration configuration)
{
_configuration = configuration;
}
private readonly IConfiguration _configuration;
但在创建公共存储库的对象时,它给出了一个错误
CommonRepository commonRepository =new CommonRepository();
没有给出与“CommonRepository.CommonRepository(IConfiguration)”的必需形式参数“configuration”对应的参数
这通常是使用依赖项注入完成的,该注入应在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)
{
...
}
}
公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
public void配置服务(IServiceCollection服务)
{
services.AddSingleton(配置);
}
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
...
}
}
ASP.Net将自动从主机向此类传递配置。我们使用它来创建一个单例,它将配置注入到所有使用IConfiguration作为参数的构造函数中。Explained您可以参考以下代码来创建和使用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 void配置服务(IServiceCollection服务)
{
...
services.addScope();
}
控制器:
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();
}
公共类HomeController:控制器
{
专用只读ILogger\u记录器;
私有只读ICommonRepository\u CommonRepository;
公共HomeController(ILogger记录器、ICommonRepository commonRepository)
{
_记录器=记录器;
_commonRepositoty=commonRepository;
}
公共IActionResult索引()
{
var str=_commonRepositoty.GetConnectionstring();
返回视图();
}
结果如下:
更多详细信息,请参阅。创建模型以存储连接字符串,从配置启动时填充该模型,并使用选项模式存储该模型。在需要时插入模型并访问连接字符串。