通常在 .NET Core 项目中,我会创建一个“boostrap”类来配置我的服务以及 DI 注册命令。这通常是一个扩展方法IServiceCollection,我可以在其中调用类似的方法,.AddCosmosDbService并且在包含该方法的静态类中所需的一切都是“自包含”的。但关键是该方法IConfiguration从Startup类中获取。
我过去曾在 Azure Functions 中使用 DI,但尚未遇到此特定要求。
当函数部署在 Azure 中时,我使用IConfiguration来绑定到具有与我的local.settings.json以及开发/生产应用程序设置中的设置匹配的属性的具体类。
/// <summary>
/// Holds configuration settings from local.settings.json or application configuration
/// </summary>    
public class CosmosDbClientSettings
{
    public string CosmosDbDatabaseName { get; set; }
    public string CosmosDbCollectionName { get; set; }
    public string CosmosDbAccount { get; set; }
    public string CosmosDbKey { get; set; }
}
public static class BootstrapCosmosDbClient
{
    /// …c# dependency-injection azure-functions .net-core-configuration
我有一个 .NET Core 控制台应用程序。我正在尝试使用以下代码检索环境变量。
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
但是,变量“environment”始终返回 null。我通过设置环境变量“ASPNETCORE_ENVIRONMENT”
控制面板 -> 系统属性 -> 环境变量 -> 系统变量
我也尝试使用命令设置环境变量set ASPNETCORE_ENVIRONMENT=development,但这也不起作用。当我F5在 Visual Studio 中调试代码 ( ) 时,该变量始终返回 null。我已经确保在我设置变量的地方或在我阅读它的代码中没有任何空格。有什么我想念的吗?
我想用它ConfigurationBuidler来读取我的appsettings.json文件。我看不出我做错了什么。
我的文件是
{
  "comment": "this gets copied to bin\\debug on build. the app updates the copy. However to remember the settings you need to paste them here",
  "col1Width": "344"
}
我的测试失败
[TestMethod]
public void TestMethod1()
{
    var configuration = Helper.LoadConfiguration("appsettings.json");
    Assert.IsTrue(configuration.Properties.Keys.Contains("col1Width")); // fails here
}
我的助手类是:
public static class Helper
{
    public static ConfigurationBuilder LoadConfiguration(string filename)
    {
        var configuration = new ConfigurationBuilder();
        var currentDirectory = System.IO.Directory.GetCurrentDirectory();
        configuration.SetBasePath(currentDirectory);
        configuration.AddJsonFile(path: filename, optional: false, reloadOnChange: true);
        configuration.Build();
        return configuration; …真的很挣扎这个 - 它应该这么难吗?
我的应用程序设置中有一个简单的对象数组:
"AppSettings": {
    "Names": [
      {
        "Id": "1",
        "Name": "Mike"
      },
      {
        "Id": "2",
        "Name": "John"
      }    
    ]
}
然后我有课
public class AppSettings
{
    public List<Names> Names { get; set; } = new List<Names>();
}
public class Names
{
    public string Id { get; set; }
    public string Name { get; set; }
}
我在我的应用程序设置中读到:
var configuration = new ConfigurationBuilder()
                            .SetBasePath(Directory.GetCurrentDirectory())
                            .AddJsonFile("appSettings.json").Build();
var config = new AppSettings();
这就是出问题的地方:
config.Names = configuration.GetSection("AppSettings:Names") //<<<< what do I do here? …我无法LogTrace(...)在我的应用程序中获得basice 输出.这是一个复制品:
.UseApplicationInsights()以便repro更清晰用以下代码替换代码ValuesController.cs:
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace WebApplication1.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        private readonly ILogger<ValuesController> logger;
        public ValuesController(ILogger<ValuesController> logger)
        {
            this.logger = logger;
        }
        [HttpGet]
        public IEnumerable<string> Get()
        {
            logger.LogError("ERROR!");
            logger.LogWarning("WARN!");
            logger.LogInformation("INFO!");
            logger.LogTrace("TRACE!");
            return new string[] { "value1", "value2" };
        }
    }
}
改变appsettings.Development.json这样的:
{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Trace",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
} …c# .net-core asp.net-core .net-core-logging .net-core-configuration
我想将以下对象与ServiceCollection中的appsettings.json数据绑定,但是我无法更改类或接口的设计:
public class TransferOptions :ITransferOptions 
{
   public IConnectionInfo Source {get;set;}
   public IConnectionInfo Destination {get;set;}
}
public class ConnectionInfo : IConnectionInfo
{
   public string UserName{get;set;}
   public string Password{get;set;}
}
public interface ITransferOptions
{
   IConnectionInfo Source {get;set;}
   IConnectionInfo Destination {get;set;}
}
public interface IConnectionInfo
{
   string UserName{get;set;}
   string Password{get;set;}
}
这是我在appsettings.json中的数据
{
"TransferOptions":{
    "Source ":{
                 "UserName":"USERNAME",
                 "Password":"PASSWORD"
              },
    "Destination":{
                 "UserName":"USERNAME",
                 "Password":"PASSWORD"
              }
   }
}
这是我在服务提供商上的配置:
var provider=new ServiceCollection()
.Configure<TransferOptions>(options => _configuration.GetSection("TransferOptions").Bind(options))
.BuildServiceProvider();
这是我收到错误的部分
无法创建“IConnectionInfo”类型的实例,因为它是抽象的或接口:
var transferOptions =_serviceProvider.GetService<IOptions<TransferOptions>>()
我使用 TopShelf 创建了一个 .net 核心控制台应用程序。但是在使用 docker (alpine-linux) 运行应用程序时出现错误。
Configuration Result:
    [Success] Name MyApp
    [Success] DisplayName MyApp
    [Success] Description My Application
    [Success] ServiceName MyApp
    Topshelf v4.1.0.177, .NET Framework v4.0.30319.42000
    Topshelf.Runtime.Windows.WindowsHostEnvironment Error: 0 : Unable to get parent process (ignored), System.DllNotFoundException: Unable to load shared library 'kernel32.dll' or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: Error loading shared library libkernel32.dll: No such file or directory
       at Topshelf.Runtime.Windows.Kernel32.CreateToolhelp32Snapshot(UInt32 dwFlags, UInt32 th32ProcessID)
       at Topshelf.Runtime.Windows.WindowsHostEnvironment.GetParent(Process …containers topshelf docker .net-core .net-core-configuration
我尝试向我的控制台应用程序添加一个记录器。所有配置都正确应用,除了Logging
程序.cs:
   private static void Main(string[] args)
    {
        var services = new ServiceCollection();
        ConfigureServices(services);
        var serviceProvider = services.BuildServiceProvider();
        serviceProvider.GetService<App>().Run();
        Console.ReadKey();
    }
    private static void ConfigureServices(ServiceCollection services)
    {
        var envName = Environment.GetEnvironmentVariable("MY_ENV") ?? DevelopmentEnvName;
        var configuration = new ConfigurationBuilder()
                            .SetBasePath(Directory.GetCurrentDirectory())
                            .AddJsonFile("appsettings.json", false)
                            .AddJsonFile($"appsettings.{envName}.json", true, true)
                            .AddEnvironmentVariables()
                            .Build();
        services.AddSingleton(configuration);
        services.AddLogging(builder =>
                            {
                                builder.AddConfiguration(configuration)
                                       .AddConsole()
                                       .AddDebug();
                            });
        ConfigureOptions(services, configuration);
        ConfigureDependencies(services);
    }
在App.Run()我尝试记录调试和信息消息
 public void Run()
 {
    _logger.LogDebug("Debug");
    _logger.LogDebug(_appOptions.Env);   //print nothing
    _logger.LogInformation("Info");
    _logger.LogInformation(_appOptions.Env);  //print Info and debug env lines
 }
appsettings.json: …
.net-core .net-core-logging .net-core-configuration .net-core-2.0
我有一个 .NET Core 3.0 控制台应用程序。我有一个 Microsoft.Extensions.Logging 记录器,并且正在使用命令行参数构建 Microsoft.Extensions.Configuration。
我的问题是“如何通过命令行参数设置日志级别?”
这篇文章https://medium.com/@dmitryzaets/legacy-net-applications-configuration-management-net-framework-4-5-1-68220335d9d8描述了如何将选项模式与 Autofac 一起使用。我试图将其翻译为与 Simple Injector 一起使用。但我没有运气。这是我的国际奥委会代码
public class IocBootstrap2
{
    private Container Container { get; }
    public IocBootstrap2()
    {
        Container = new Container();
        var configurationBuilder = new ConfigurationBuilder()
            .SetBasePath(Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Configuration"))
            .AddJsonFile("settings.json", optional: false, reloadOnChange: true);
        var configuration = configurationBuilder.Build();
        //Register Options
        Container.Register(typeof(IOptions<>), typeof(OptionsManager<>));
        Container.Register(typeof(IOptionsMonitor<>), typeof(OptionsMonitor<>));
        Container.Register(typeof(IOptionsFactory<>), typeof(OptionsFactory<>));
        Container.Register(typeof(IOptionsMonitorCache<>), typeof(OptionsCache<>));
        // Register ConfigurationOptions
        Container.RegisterConfigurationOptions2<MailingOptions>(configuration.GetSection("mailing"));
    #if DEBUG
        Container.Verify();
    #endif   
 }
}
public static class ConfigurationSetupExtensions2
{
    public static void RegisterConfigurationOptions2<TOptions>(this Container container, IConfiguration config)
        where TOptions : class
    {
        container.Register(typeof(IOptionsChangeTokenSource<TOptions>), …configuration configurationmanager legacy-code simple-injector .net-core-configuration