Tau*_*qir 3 .net-core asp.net-core
我知道 .net core 已经用 appsetting.json 替换了 app.config 文件。然而,这个文件似乎只为 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这允许我针对 DbContext运行迁移和基于控制台的实用程序。您没有指定您需要什么样的配置 - 所以这只是一个例子。但希望您可以根据自己的需要进行调整。
| 归档时间: |
|
| 查看次数: |
6865 次 |
| 最近记录: |