如何从ASP.NET Core读取.NET Standard Class库项目中的连接字符串

问题描述 投票:1回答:2

在我的解决方案中,我有一个ASP.NET Core Web项目和一个.NET Standard类库项目。类库项目是数据访问层,我想从我的数据访问层中的appsettings.json(ASP.NET核心项目)读取连接字符串。

我找到了很少的答案,例如Andrii Litvinov看起来很容易实现,但他也提到了通过依赖注入实现。我不想选择简单的快捷方式,但寻找依赖注入实现?

我不确定在我的类库中是否有appsettings.json,然后通过IConfigurationRoot注册它是更好的选择(如JRB所述的here)但在我的场景中,连接字符串位于web项目的appsettings.json文件中我不想在我的类库项目中使用构造函数依赖注入实现来使用连接字符串。

c# dependency-injection connection-string asp.net-core-2.0 class-library
2个回答
2
投票

您可以注入实现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核心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();
    }
}

现在,当您的类库中的代码被执行时,ctor将获得您在Web应用程序中设置的IConfiguration实例

注意:如果您愿意,可以创建强类型设置类see here for more information


1
投票

我会建议选项模式。您可以使用配置数据创建类,例如:

public class ConnectionStringConfig
{
    public string ConnectionString { get; set; }
}

在Startup上注册:

public void ConfigureServices(IServiceCollection services)
{
   ...    
   services.Configure<ConnectionStringConfig>(Configuration);
}

并注入您的数据访问层

private readonly ConnectionStringConfig config;

public Repository(IOptions<ConnectionStringConfig> config) 
{
    this.config = config.Value;
}
© www.soinside.com 2019 - 2024. All rights reserved.