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

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

问题描述

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

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

在Google上搜索时,我发现以下链接 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时,您将使用依赖注入-在这里您将读取conn字符串从网络api的配置中

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天全站免登陆