如何在类库中添加配置文件,然后是 .NET Core 1.1 的连接字符串 [英] how to add config file in Class Library, followed by connection string for .NET Core 1.1

查看:25
本文介绍了如何在类库中添加配置文件,然后是 .NET Core 1.1 的连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发具有数据访问层的 n 层应用程序.它独立于任何其他应用程序.我已经为 .NET Core 1.1 创建了类库,我可以看到依赖项文件夹但看不到任何配置/JSON 文件.我想知道,我可以在类库项目中添加 AppSetting.JSON 文件吗?其次是如何添加连接字符串.我知道要覆盖 DbContext 类中的 ConfigureBuilder --> SQLServerConnection 但我想保留在单独的配置文件中并引用这些连接字符串.

I am working on n-tier application, where I have Data Access Layer. which is independent to any other application. I have create Class Library for .NET Core 1.1, I can see dependencies folder but not any config/JSON file. I want to know, Can I add AppSetting.JSON file in class library project? followed by how can I add connection string. I am aware to override ConfigureBuilder in DbContext class --> SQLServerConnection but I want to keep in separate config file and refer to these connection strings.

还要注意,这个类库不会直接链接到 ASP.NET 应用程序

Also to note, This class library will not link to ASP.NET application directly

在谷歌上搜索时,我发现了以下链接 https://www.stevejgordon.co.uk/project-json-replaced-by-csproj 但我的问题仍然存在,我在哪里以及如何为类库项目添加连接字符串?

While searching on google, I have found following link https://www.stevejgordon.co.uk/project-json-replaced-by-csproj but my question remains, where and how I add connection string for Class Library project?

推荐答案

你有点搞错了.您不想为您的 DAL 程序集提供配置文件,您只是希望您的 DAL 对配置一无所知!

You've kind of got this the wrong way round. You dont want to have a config file for your DAL assembly, you simply want your DAL to know nothing at all about configuration!

通常,您为 DAL 配置的只是一个连接字符串,这可以很容易地传递给构造函数:

Typically, all you configure for a DAL is a conection string and this can easily be passed in on a constructor:

public class MyRepository : IMyRepository
{
    public MyRepository(string connectionString){ ... }
}

当你在 webapi 之类的东西中使用这个 DAL 时,你很可能会使用依赖注入 - 在这里你可以从 web api 的配置中读取 conn 字符串

When you use this DAL in something like a webapi chances are you'll be using Dependency Injection - and it's here you would read the conn string from the web api's configuration

public void ConfigureServices(IServiceCollection services)
{
    var connectionString = Configuration.GetConnectionString("MyConnectionString");
    services.AddScoped<IMyRepository>(sp => new MyRepository(connectionString));
}

这篇关于如何在类库中添加配置文件,然后是 .NET Core 1.1 的连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆