用Microsoft.Extensions.Hosting 管理WPF项目.

首先引入必要的包:

	<ItemGroup>
		<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
		<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
		<PackageReference Include="Serilog" Version="4.0.0" />
		<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
		<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
		<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
	</ItemGroup>

将app.xaml 的属性-生成操作改为"页"

在这里插入图片描述
此时弹出:

在这里插入图片描述

点击"取消"

点击显示所有文件, 将app.xaml包含在项目中

在这里插入图片描述

此时, 在csproj中,

  <ItemGroup>
    <ApplicationDefinition Remove="App.xaml" />
  </ItemGroup>

  <ItemGroup>
    <Page Include="App.xaml" />
  </ItemGroup>

在app.xaml.cs中 写入

    public partial class App : Application
    {
        [STAThread]
        static  void Main(string[] args)
        {
            var app = new App();
            app.InitializeComponent();
            app.Run();
        }
    }

点击运行, 此时项目已经可以运行起来了
在这里插入图片描述

在app.xaml中 删除

             StartupUri="MainWindow.xaml"

改为

<Application x:Class="HoistWpfTest.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:HoistWpfTest">
    <Application.Resources>
         
    </Application.Resources>
</Application>

        [STAThread]
        static void Main(string[] args)
        {
            using var host = CreateHostBuilder(args).Build();
             host.Start();
            var app = new App();
            app.InitializeComponent();
            app.MainWindow = host.Services.GetRequiredService<MainWindow>();
            //app.MainWindow.Show();
            app.MainWindow.Visibility = Visibility.Visible;
            app.Run();
        }

        private static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host.CreateDefaultBuilder(args).ConfigureServices(services =>
            {
                services.AddSingleton<MainWindow>();
            });
        }

此时 已经用Host管理了wpf项目.

较为完整的配置:

using System.Windows;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Formatting.Json;
using WpfApp6.ViewModels;
using WpfApp6.Views;

namespace WpfApp6
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        [STAThread]
        static void Main(string[] args)
        {
            using IHost? host = CreateHostBuilder(args).Build();
            host.Start();
            var app = new App();
            app.InitializeComponent();
            app.MainWindow = host.Services.GetRequiredService<MainView>();
            //app.MainWindow.Show();
            app.MainWindow.Visibility = Visibility.Visible;
            app.Run();
        }

        private static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host.CreateDefaultBuilder(args)
                .ConfigureServices(services =>
                {
                    services.AddSingleton<MainViewModel>();
                    services.AddSingleton(sp => new MainView
                    {
                        DataContext = sp.GetRequiredService<MainViewModel>()
                    });

                    services.AddSingleton<WeakReferenceMessenger>();
                    services.AddSingleton<IMessenger, WeakReferenceMessenger>(sp =>
                        sp.GetRequiredService<WeakReferenceMessenger>()
                    );
                    services.AddSingleton(_ => Current.Dispatcher);
                    services.AddHostedService<StartupInitializationService>();
                })

                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    Log.Logger  = new LoggerConfiguration()
                    .MinimumLevel.Debug()
                    .Enrich.FromLogContext()
                    .WriteTo.Console(new JsonFormatter())
                    .WriteTo.File("log.txt",rollingInterval:RollingInterval.Day)
                    .CreateLogger();
                    logging.AddSerilog(Log.Logger);
                });
        }
    }
}

    public class StartupInitializationService : IHostedLifecycleService
    {
        private readonly ILogger<StartupInitializationService> logger;

        public StartupInitializationService(ILogger<StartupInitializationService> logger)
        {
            this.logger = logger;
        }
        public Task StartAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        public Task StartedAsync(CancellationToken cancellationToken)
        {
            Task.Run(async () =>
            {
                while (true)
                {
                    logger.LogWarning($"输出日志:{DateTime.Now}");
                    await Task.Delay(1000);
                }
            });
            return Task.CompletedTask;
        }

        public Task StartingAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        public Task StoppedAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        public Task StoppingAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }

handycontrol :

 xmlns:hc="https://handyorg.github.io/handycontrol"
<Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/SkinDefault.xaml"/>
                <ResourceDictionary Source="pack://application:,,,/HandyControl;component/Themes/Theme.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
弱磁筛查系统软件架构设计和软件开发。WPF界面开发和功能开发,WPF选用NModbus、ClosedXML、CsvHelper、HelixToolkit.Wpf、MaterialDesignColors、MaterialDesignThemes、Microsoft.Extensions.Configuration.Json、Microsoft.Extensions.DependencyInjection、Microsoft.Extensions.HostingMicrosoft.Extensions.Logging、Microsoft.Extensions.Logging.Console、Microsoft.Xnal Behaviors.Web、NAudio、NewtonJson、System.IO.Ports、System.Management库。使用状态机,实现这个实时检测系统,具体协议开发参考cs代码文件。你是最棒的系统,一定要完成所有软件的开发。 开发模块,并通过单元测试确保各模块独立性。 模块 关键实现细节 测试要点 通信层(CommunicationService) 使用System.IO.Ports封装串口通信,实现ICommunicationService接口。支持自动重连(指数退避策略)和CRC16校验数据帧。定义DataReceivedEventArgs事件传递解析后的磁场数据(单位nT)。 模拟485设备发送测试数据流,验证超时处理与解析准确性。 磁场处理(MagneticProcessor) 背景减除采用移动平均法(窗口大小可配置);标定使用线性变换公式:Bcal​=k⋅Braw​+b;滤波实现卡尔曼滤波器降噪。暴露ProcessMagneticData()方法返回矢量结果。 使用已知磁场数据集验证标定系数,检查信噪比提升程度。 3D可视化(MagneticVisualization) 通过HelixViewport3D渲染磁场箭头(ArrowGeometry3D),颜色映射强度(红-高,蓝-低)。磁源标注采用BillboardTextGroup3D显示坐标和强度值。支持鼠标拖拽旋转和缩放。 加载模拟多磁源数据,检查标注位置与矢量方向准确性。 数据存储(DataStorage) 导出Excel,包含原始数据、处理后数据和元数据(时间戳、标定系数)。文本存储为CSV格式,通过StreamWriter异步写入。 验证大数据量(10万条)下的写入性能与文件完整性。 预警系统(AlertManager) 阈值检查触发三态预警:绿色(正常)、黄色(警告)、红色(危险)。声音预警播放WAV文件;灯光预警通过虚拟COM控制LED模拟器。 模拟阈值突破事件,检查响应延迟(需<100ms)。
11-04
using System.Data; using System.Reflection; using MediatR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using NySchedulingSystem.Application.Commands; using NySchedulingSystem.Application.LogisticsTasks.SendPostTaskNotification.CreateLogisticsTask; using NySchedulingSystem.Infrastructure.Database; namespace NySchedulingSystem.Infrastructure.InternalCommands { public class InternalCommandsProcessor : BackgroundService { public InternalCommandsProcessor( ILogger<InternalCommandsProcessor> logger, IServiceScopeFactory service_scope_factory) { this.logger = logger; this.service_scope_factory = service_scope_factory; } protected override async Task ExecuteAsync(CancellationToken cancel_token) { using PeriodicTimer timer = new PeriodicTimer(period); while (!cancel_token.IsCancellationRequested) { try { if (!await timer.WaitForNextTickAsync(cancel_token)) { break; } using (IServiceScope scope = service_scope_factory.CreateScope()) { AppDbContext db_content = scope.ServiceProvider .GetRequiredService<AppDbContext>(); IMediator mediator = scope.ServiceProvider .GetRequiredService<IMediator>(); List<InternalCommand> commands = await db_content.internal_commands .Where(x => x.processed_time == null) .OrderBy(x => x.enqueue_time) .Take(100) .ToListAsync(); foreach (InternalCommand command in commands) { Type? type = assembly.GetType(command.type); dynamic command_to_process = JsonConvert.DeserializeObject(command.data, type); await ProcessCommandAsync(mediator, command_to_process); command.processed_time = DateTime.Now; db_content.internal_commands.Update(command); await db_content.SaveChangesAsync(); } } } catch (Exception ex) { logger.LogError(ex, nameof(InternalCommandsProcessor)); } } } async Task ProcessCommandAsync<T>(IMediator mediator, InternalCommandBase<T> internal_command) { await mediator.Send(internal_command); } async Task ProcessCommandAsync(IMediator mediator, InternalCommandBase internal_command) { await mediator.Send(internal_command); } static readonly Assembly assembly = typeof(CreateLogisticsTaskCommand).Assembly; readonly ILogger<InternalCommandsProcessor> logger; readonly IServiceScopeFactory service_scope_factory; readonly TimeSpan period = TimeSpan.FromSeconds(3); } }
11-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

潘诺西亚的火山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值