add following packages
<ItemGroup>
<PackageReference Include="microsoft.extensions.configuration" Version="6.0.0" />
<PackageReference Include="microsoft.extensions.configuration.binder" Version="6.0.0" />
<PackageReference Include="microsoft.extensions.configuration.json" Version="6.0.0" />
<PackageReference Include="microsoft.extensions.dependencyinjection" Version="6.0.0" />
<PackageReference Include="microsoft.extensions.options" Version="6.0.0" />
</ItemGroup>
sample code
class Config
{
public string Name { get; set; }
public int Age { get; set; }
public Proxy Proxy { get; set; }
public override string ToString()
{
return $"name:{Name}, age:{Age}, proxy:{Proxy}";
}
}
class Proxy
{
public string Server { get; set; }
public int Port { get; set; }
public override string ToString()
{
return $"server:{Server}, port:{Port}";
}
}
class TestController
{
// IOptions: 只读配置,不追踪变化
// IOptionsSnapshot: 在scope内配置不会变,出了scope或进入新scope就会更新变化
// IOptionsMonitor: 追踪配置变化
private IOptionsSnapshot<Config> optConfig { get; }
public TestController(IOptionsSnapshot<Config> config)
{
optConfig = config;
}
public void Test()
{
System.Console.WriteLine(optConfig.Value);
}
}
从json文件读取
class Program
{
static void Main(string[] args)
{
ServiceCollection services = new ServiceCollection();
services.AddScoped<TestController>();
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddJsonFile("config.json", true, true);
IConfigurationRoot configRoot = builder.Build();
services.AddOptions()
.Configure<Config>(e => configRoot.Bind(e)); // 绑定Config对象
//.Configure<Proxy>(e => configRoot.GetSection("proxy").Bind(e)); // 也可以只绑定Proxy对象
using (ServiceProvider provider = services.BuildServiceProvider())
{
int count = 5;
while (count-- > 0)
{
using (IServiceScope scope = provider.CreateScope())
{
IServiceProvider sp = scope.ServiceProvider;
TestController test1 = sp.GetService<TestController>();
test1.Test();
}
System.Console.WriteLine($"press return to continue, {count} remaining...");
System.Console.ReadLine();
// change config value here, would reflect the changes in above Test() call.
}
}
}
}
从命令行读取
static void Main(string[] args)
{
ServiceCollection services = new ServiceCollection();
services.AddScoped<TestController>();
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddCommandLine(args); // 加入命令行支持
builder.AddEnvironmentVariables("prefix_"); // 加入环境变量支持,建议使用前缀,避免和其他系统冲突。
IConfigurationRoot configRoot = builder.Build();
services.AddOptions()
.Configure<Config>(e => configRoot.Bind(e)); // bind to Config
//.Configure<Proxy>(e => configRoot.GetSection("proxy").Bind(e)); // bind to Proxy part only.
using (ServiceProvider provider = services.BuildServiceProvider())
{
TestController test1 = provider.GetService<TestController>();
test1.Test();
}
}
// 命令行调用
dotnet run --name abc --age 22 --proxy:server abc.ccc --proxy:port 888