加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

.net-core – 用于.NET Core控制台应用程序的ASP.NET Core配置

发布时间:2020-12-15 22:42:46 所属栏目:asp.Net 来源:网络整理
导读:ASP.NET Core支持新配置系统,如下所示: https://docs.asp.net/en/latest/fundamentals/configuration.html .NET Core控制台应用程序中还支持这种模式吗? 如果不是以前的app.config和ConfigurationManager模型的替代品? 解决方法 您可以使用此代码段.它包
ASP.NET Core支持新配置系统,如下所示:
https://docs.asp.net/en/latest/fundamentals/configuration.html

.NET Core控制台应用程序中还支持这种模式吗?

如果不是以前的app.config和ConfigurationManager模型的替代品?

解决方法

您可以使用此代码段.它包括配置和DI.
public class Program
{
    public static ILoggerFactory LoggerFactory;
    public static IConfigurationRoot Configuration;

    public static void Main(string[] args)
    {
        Console.OutputEncoding = Encoding.UTF8;

        string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

        if (String.IsNullOrWhiteSpace(environment))
            throw new ArgumentNullException("Environment not found in ASPNETCORE_ENVIRONMENT");

        Console.WriteLine("Environment: {0}",environment);

        var services = new ServiceCollection();

        // Set up configuration sources.
        var builder = new ConfigurationBuilder()
            .SetBasePath(Path.Combine(AppContext.BaseDirectory))
            .AddJsonFile("appsettings.json",optional: true);
        if (environment == "Development")
        {

            builder
                .AddJsonFile(
                    Path.Combine(AppContext.BaseDirectory,string.Format("..{0}..{0}..{0}",Path.DirectorySeparatorChar),$"appsettings.{environment}.json"),optional: true
                );
        }
        else
        {
            builder
                .AddJsonFile($"appsettings.{environment}.json",optional: false);
        }

        Configuration = builder.Build();

        LoggerFactory = new LoggerFactory()
            .AddConsole(Configuration.GetSection("Logging"))
            .AddDebug();

        services
            .AddEntityFrameworkNpgsql()
            .AddDbContext<FmDataContext>(o => o.UseNpgsql(connectionString),ServiceLifetime.Transient);

        services.AddTransient<IPackageFileService,PackageFileServiceImpl>();

        var serviceProvider = services.BuildServiceProvider();

        var packageFileService = serviceProvider.GetRequiredService<IPackageFileService>();

        ............
    }
}

哦,不要忘了在project.json中添加

{
  "version": "1.0.0-*","buildOptions": {
    "emitEntryPoint": true,"copyToOutput": {
      "includeFiles": [
        "appsettings.json","appsettings.Integration.json","appsettings.Production.json","appsettings.Staging.json"
      ]
    }
  },"publishOptions": {
    "copyToOutput": [
      "appsettings.json","appsettings.Staging.json"
    ]
  },...
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读