Lea*_*rve 4 c# connection-string dependency-injection class-library asp.net-core-2.0
在我的解决方案中,我有一个 ASP.NET Core Web 项目和一个 .NET Standard 类库项目。类库项目是数据访问层,我想从我的数据访问层中的 appsettings.json(ASP.NET Core 项目)读取连接字符串。
我找到了几个答案,例如Andrii Litvinov看起来很容易实现,但他也提到了通过依赖注入来实现。我不想选择简单的快捷方式而是寻找依赖注入实现?
我不确定在我的类库中是否有 appsettings.json 然后通过 IConfigurationRoot 注册它是更好的选择(如JRB 在此解释)但在我的场景中,连接字符串位于 web 项目的 appsettings.json 文件中,并且我不想在我的类库项目中使用构造函数依赖注入实现来使用连接字符串。
您可以注入实现IConfiguration
See Here的类的实例
让我们假设在您的 .net 核心应用程序中,您有一个如下所示的配置文件:
{
  "App": {
    "Connection": {
      "Value": "connectionstring"
    }
  }
}
在您的数据访问层(类库)中,您可以依赖 IConfiguration
public class DataAccess : IDataAccess
{
    private IConfiguration _config;
    public DataAccess(IConfiguration config)
    {
        _config = config;
    }
    public void Method()
    {
        var connectionString = _config.GetValue<string>("App:Connection:Value"); //notice the structure of this string
        //do whatever with connection string
    }
}
现在,在您的 ASP.net Core Web 项目中,您需要“连接”您的依赖项。在 Startup.cs 中,我正在使用它(来自默认样板模板)
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public IConfiguration Configuration { get; }
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddSingleton<IConfiguration>(Configuration); //add Configuration to our services collection
        services.AddTransient<IDataAccess, DataAccess>(); // register our IDataAccess class (from class library)
    }
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseMvc();
    }
}
现在,当您的类库中的代码被执行时,构造函数会收到IConfiguration您在 Web 应用程序中设置的实例
注意:如果您愿意,您可以创建强类型设置类,请参阅此处了解更多信息
| 归档时间: | 
 | 
| 查看次数: | 10219 次 | 
| 最近记录: |