asp.net-core - appsettings.json 文件不在 .net 核心控制台项目中
问题描述
我了解 .net 核心已将 app.config 文件替换为 appsetting.json。然而,这个文件似乎只为 ASP.net 项目添加。事实上,它甚至在添加项目列表中都不可用。我发现这篇文章列出了需要添加的包:
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.FileExtensions
- Microsoft.Extensions.Configuration.Json
我添加了所有这些,它确实为我提供了添加 json 配置文件的选项,但仍然不是App Settings File
仅在 ASP.Net Core 下可用的选项。我试图了解为什么非 Web 项目不需要配置以及配置 .net 核心控制台应用程序的推荐方法是什么。提前致谢。
解决方案
非 web 项目可能需要也可能不需要配置。但是,正如您所注意到的,Visual Studio 不会使用appsettings.json
. 显然,您可以将其作为 json 文件添加到项目中。一旦拥有它,挑战就是如何利用它。我经常在实体框架实用程序中使用配置对象和依赖注入。
例如,
public static class Program
{
private static IConfigurationRoot Configuration { get; set; }
public static void Main()
{
IConfigurationBuilder builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
IServiceCollection services = new ServiceCollection();
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddScoped<IMyService, MyService>();
IServiceProvider provider = services.BuildServiceProvider();
IMyService myService = provider.GetService<IMyService>();
myService.SomeMethod();
}
public class TemporaryDbContextFactory : IDesignTimeDbContextFactory<MyDbContext>
{
public MyDbContext CreateDbContext(string[] args)
{
IConfigurationBuilder configBuilder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
IConfigurationRoot configuration = configBuilder.Build();
DbContextOptionsBuilder<MyDbContext> builder = new DbContextOptionsBuilder<MyDbContext>();
builder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
return new MyDbContext(builder.Options);
}
}
}
这使我可以针对 DbContext运行迁移和基于控制台的实用程序。你没有指定你需要什么样的配置——所以这只是一个例子。但希望您可以根据自己的需要进行调整。
推荐阅读
- three.js - 如何在 Angular 应用程序中使用自定义着色器?
- python-3.x - Jupyter 认证问题
- python - Pandas:有没有办法将列中的值组合在一起?
- vba - 在 R1C1 公式中使用时,带小数的变量会转换为 2 位数字
- r - 在不丢失信息的情况下减少数据
- javascript - Scriptable Java Transform Spring 云数据流
- lua - Lua - 难以理解 OOP
- excel - Excel 2016 VBA - 状态栏未显示完整消息
- angularjs - $scope.$on $locationChangeStart 保留 URL 但显示新视图
- java - Spring boot 2 - REST 控制器测试在 org.springframework.hateoas.PagedResources 上引发异常