我发现用。net Core 3+最容易做到以下几点。我发现所有使用HostBuilders等的其他方法都有点啰嗦,而且可读性不强。这不是专门针对ASP的。但是你可以调整它…
这里有一个工作示例:https://github.com/NotoriousPyro/PyroNexusTradingAlertBot/blob/develop/PyroNexusTradingAlertBot/Program.cs
创建json:
{
"GlobalConfig": {
"BlacklistedPairs": [ "USD", "USDT", "BUSD", "TUSD", "USDC", "DAI", "USDK" ]
},
"CoinTrackingConfig": {
"Cookie1": "",
"Cookie2": "",
"ApiKey": "",
"ApiSecret": "",
"UpdateJobs": [
{
"Name": "Binance",
"Path": "binance_api",
"JobId": 42202
},
{
"Name": "Bitfinex",
"Path": "bitfinex_api",
"JobId": 9708
}
]
},
"DiscordConfig": {
"BotToken": ""
}
}
创建json对象的类:
class GlobalConfig
{
public string[] BlacklistedPairs { get; set; }
}
class CoinTrackingConfig
{
public string Cookie1 { get; set; }
public string Cookie2 { get; set; }
public string ApiKey { get; set; }
public string ApiSecret { get; set; }
public List<CoinTrackingUpdateJobs> UpdateJobs { get; set; }
}
class CoinTrackingUpdateJobs
{
public string Name { get; set; }
public string Path { get; set; }
public int JobId { get; set; }
}
class DiscordConfig
{
public string BotToken { get; set; }
}
创建一个helper类:
private class Config
{
private IConfigurationRoot _configuration;
public Config(string config) => _configuration = new ConfigurationBuilder()
.AddJsonFile(config)
.Build();
public T Get<T>() where T : new()
{
var obj = new T();
_configuration.GetSection(typeof(T).Name).Bind(obj);
return obj;
}
}
服务提供者选项和服务构造函数:
public class DiscordServiceOptions
{
public string BotToken { get; set; }
}
public DiscordService(IOptions<DiscordServiceOptions> options, ILogger<DiscordService> logger)
{
_logger = logger;
_client = new DiscordSocketClient();
_client.Log += Log;
_client.Ready += OnReady;
_client.Disconnected += OnDisconnected;
_client.LoginAsync(TokenType.Bot, options.Value.BotToken);
_client.StartAsync();
}
像这样初始化它(将配置传递给服务提供者- IOptions将在服务构建时传递进来):
static async Task Main(string[] args)
{
var _config = new Config("config.json");
var globalConfig = config.Get<GlobalConfig>();
var coinTrackingConfig = config.Get<CoinTrackingConfig>();
var discordConfig = config.Get<DiscordConfig>();
_services = new ServiceCollection()
.AddOptions()
.Configure<DiscordServiceOptions>(options =>
{
options.BotToken = discordConfig.BotToken;
})
.AddSingleton<IDiscordService, DiscordService>()
.AddLogging(logging =>
{
logging.SetMinimumLevel(LogLevel.Trace);
logging.AddNLog(new NLogProviderOptions
{
CaptureMessageTemplates = true,
CaptureMessageProperties = true
});
})
.BuildServiceProvider();
}