ASP.NET Core 项目模板自带appsettings.json
和appsettings.Development.json
,默认添加在CreateDefaultBuilder中。 .
因为带有 DbContext
的项目与我的 ASP.NET Core 项目 (MyProject.Data
) 是分开的,所以我需要为 IDesignTimeDbContextFactory
实现我的上下文,以便 Add-Migration
和 Update-Database
等命令正常工作。我不想为我的 IDesignTimeDbContextFactory
硬编码我的连接字符串,而是在两个项目中重复使用该配置。
我的解决方案很少,但我想根据您的经验和意见了解最合理的解决方案。
- 在我的 ASP.NET Core(UI 层)项目中实现
IDesignTimeDbContextFactory
。 - 在我的
MyProject.Data
项目中实现IDesignTimeDbContextFactory
,并将appsettings.json
移动到某个根目录或configuration
(位于根目录)项目之间共享的目录。 - 为数据库创建单独的配置文件,例如
database.json
,将其放在我的.sln
文件旁边。
我该如何分享?
编辑:
这里有类似的问答:ConnectionString from appsettings.json in Data Tier with Entity Framework Core但它没有回答我的问题。它根本没有说明数据层。我不想重复使用逻辑来添加数据库上下文。 我想在两个项目中重复使用连接字符串以避免重复连接字符串。
最佳答案
虽然通常建议在中央位置进行配置,但没有任何限制单个项目管理自己的配置。
在以下示例中,连接字符串信息存储在外部 datasettings.json 文件中
{
"ConnectionStrings": {
"DefaultConnection": "connection string here"
}
}
该层的自包含设置扩展的一个简单示例可能如下所示
public static class MyServiceCollectionExtensions {
public static IServiceCollection AddMyDataLayer(this IServiceCollection services, string name = "DefaultConnection") {
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("datasettings.json"); //<<< just an example
var connectionStringConfig = builder.Build();
services
.AddEntityFrameworkSqlServer()
.AddDbContext<YourDbContext>((serviceProvider, options) =>
options
.UseSqlServer(connectionStringConfig.GetConnectionString(name))
);
return services;
}
}
并添加到启动
using my.data.layer;
//...
public void ConfigureServices(IServiceCollection services) {
//...
services.AddMyDataLayer();
//...
}
本例中的数据层管理自己的配置。它的设置文件在应用程序设置之外。
还有扩展空间,因为其他选项也可以在本地管理,并且适用于例如即插即用的交 key 插件解决方案。
Configuration in ASP.NET Core的模块性质允许这样的灵 active 。
关于c# - 在多层项目中管理配置的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50742964/