WPF App
主机配置
Microsot.Extension.Hosting
一键启动(配置文件、依赖注入,日志)
csharp
// App.xaml.cs 中定义 IHost
private readonly IHost _host = Host.CreateDefaultBuilder().ConfigureAppConfiguration(c =>
{
_ = c.SetBasePath(Environment.CurrentDirectory);
// 配置文件
// _ = c.AddJsonFile("appsettings.json");
_ = c.AddIniFile("appsettings.ini");
}).ConfigureServices((c, s) =>
{
// 后台服务 BackgroundService
_ = s.AddHostedService<ApplicationHostService>();
_ = s.AddHostedService<WorkerService>();
// 视图
_ = s.AddSingleton<MainWindow>();
_ = s.AddSingleton<ViewModels.MainWindowViewModel>();
_ = s.AddSingleton<ModuleForLogView>();
_ = s.AddSingleton<ViewModels.ModuleForLogViewModel>();
// 依赖注入
_ = s.AddScoped<IMonkey, Monkey>();
}).ConfigureLogging((c, l) =>
{
l.ClearProviders();
// Logging 自带的仅能输出至控制台
// NLog 扩展 记录到文件
l.AddNLog();
}).Build();
构造函数注入,读取配置信息
更丰富的注入还需要 Autofac
配置文件支持 json,ini 等,使用_config["A:B"]写法读取配置项
csharp
private readonly IMonkey _monkeyService;
private readonly ILogger<ModuleForLogViewModel> _logger;
private readonly IConfiguration _config;
public ModuleForLogViewModel(IMonkey monkeyService, ILogger<ModuleForLogViewModel> logger, IConfiguration config)
{
_monkeyService = monkeyService;
_logger = logger;
_config = config;
// 读取配置
var s = _config["项目:年份"];
_logger.LogInformation(s);
MessageBox.Show(_monkeyService.Act());
}