.NET Core 3.x 控制台应用调用 IConfiguration 和 依赖注入
.NET Core 3.x 控制台应用调用 IConfiguration 和 依赖注入
IConfiguration
IConfiguration
有两个包
Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json
具体使用
先创建 appsettings.json
,注意两个选项
这个 Json 文件内容
{
"RabbitMQ": {
"HostName": "192.168.0.151",
"Port": "5672",
"Administrator": {
"Username": "administrator",
"Password": "123456"
}
}
}
然后是创建对象,两种方法
方法一
private static IConfiguration _configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();
方法二
private static IConfiguration _configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
完整代码
class Program
{
private static IConfiguration _configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();
static void Main(string[] args)
{
Console.WriteLine(Program._configuration["RabbitMQ:HostName"]);
}
}
运行结果
依赖注入
添加一个包
Microsoft.Extensions.DependencyInjection
这个配置就很简单了,根据ASP.NET Core
的写
IServiceCollection services = new ServiceCollection();
举个例子,IConfiguration
的依赖注入
IServiceCollection services = new ServiceCollection();
services.AddSingleton<IConfiguration>(serviceProvider =>
{
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("appsettings.json");
return configurationBuilder.Build();
});
创建对象
IConfiguration configuration = services.BuildServiceProvider().GetService<IConfiguration>();
Console.WriteLine(configuration["RabbitMQ:HostName"]);
运行结果
配置普通类
这个就跟ASP.NET Core
一样了
比如我有一个Test
类,你也可以先写一个接口,再写一个类
public class Test
{
private readonly IConfiguration _configuration;
public Test(IConfiguration configuration)
{
this._configuration = configuration;
}
public void Foo()
{
Console.WriteLine(this._configuration["RabbitMQ:HostName"]);
}
}
配置只有一句
services.AddSingleton<Test>();
完整代码
static void Main(string[] args)
{
IServiceCollection services = new ServiceCollection();
services.AddSingleton<IConfiguration>(serviceProvider =>
{
IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddJsonFile("appsettings.json");
return configurationBuilder.Build();
});
services.AddSingleton<Test>();
Test t = services.BuildServiceProvider().GetService<Test>();
t.Foo();
}
运行结果
如果需要在其它类中调用容器,只需要将IServiceProvider serviceProvider
作为参数传递即可,或者作为静态字段写类里面,单例模式也行
还有一个坑
IServiceProvider serviceProvider
应该在配置完服务后再使用services.BuildServiceProvider()
赋值一次
当然,也可以用AutoFac
,C# 自带的容器也可以,使用方式基本一致